Skip to content

Commit 856fe7a

Browse files
committed
Add classes for ArrayList exercises
1 parent 75586a0 commit 856fe7a

13 files changed

+288
-32
lines changed

src/main/java/collections/arraylist/ArrayListExercises.java renamed to src/main/java/collections/arraylist/ArrayListComparableExercise.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,9 @@
22

33
import java.util.ArrayList;
44
import java.util.Comparator;
5-
import java.util.Iterator;
65
import java.util.List;
76

8-
public class ArrayListExercises {
7+
public class ArrayListComparableExercise {
98

109
static class Employee implements Comparable<Employee> {
1110
String name;

src/main/java/collections/arraylist/ArrayListComparatorDemo2.java

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import java.util.List;
77

88
class Vehicle4 {
9-
109
String brand;
1110
Integer makeYear;
1211

@@ -27,7 +26,6 @@ public static void main(String[] args) {
2726
list.add(new Vehicle4("BMW", 2015));
2827
System.out.println("Sorting by brand name");
2928
Collections.sort(list, new Comparator<Vehicle4>() {
30-
3129
@Override
3230
public int compare(Vehicle4 o1, Vehicle4 o2) {
3331
return o1.brand.compareTo(o2.brand);
@@ -40,7 +38,6 @@ public int compare(Vehicle4 o1, Vehicle4 o2) {
4038

4139
System.out.println("Sorting by make year");
4240
Collections.sort(list, new Comparator<Vehicle4>() {
43-
4441
@Override
4542
public int compare(Vehicle4 o1, Vehicle4 o2) {
4643
return o1.makeYear.compareTo(o2.makeYear);

src/main/java/collections/arraylist/ArrayListComparatorDemo3.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import java.util.List;
66

77
class Vehicle5 {
8-
98
String brand;
109
Integer makeYear;
1110

src/main/java/collections/arraylist/docs/exercises.md

Lines changed: 61 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# `ArrayList` exercises
22

3-
## Java Exercise 1: Implement Comparable for Sorting Custom Objects
3+
## Exercise 1: Implement Comparable for Sorting Custom Objects
44

55
**Objective**: Learn how to use the `Comparable` interface to sort custom objects in Java.
66

@@ -22,7 +22,7 @@ Each `Student` object has two properties:
2222

2323
---
2424

25-
## Java Exercise 2: Custom Sorting with Multiple Conditions
25+
## Exercise 2: Custom Sorting with Multiple Conditions
2626

2727
**Objective**: Expand your understanding of the `Comparable` interface by implementing custom sorting logic that uses multiple conditions.
2828

@@ -44,31 +44,71 @@ If two books were published in the same year, secondary sorting should be based
4444

4545
---
4646

47-
## Java Exercise 3: Understanding the Importance of Consistency with equals
47+
## Exercise 3: Basic ArrayList Operations
4848

49-
**Objective**: Understand the importance of consistency between the `compareTo` method of the `Comparable` interface and the `equals` method from the `Object` class.
49+
**Objective**: Learn basic operations of the `ArrayList`, such as adding, removing, and accessing elements.
5050

51-
**Background**: It is strongly recommended (though not strictly required) that `(x.compareTo(y)==0) == (x.equals(y))`.
52-
Failure to adhere to this condition may cause unpredictable behavior when such objects are used in Java collections.
51+
**Task**:
52+
53+
- Create an `ArrayList` of integers.
54+
- Add several integers to the list.
55+
- Remove specific integers from the list using index and object removal methods.
56+
- Access various elements in the list and print them.
57+
58+
**Expected Output**: Demonstrate the current state of the list after each operation, showing successful addition, removal, and access of elements.
59+
60+
---
61+
62+
## Exercise 4: Implementing a Dynamic Array
63+
64+
**Objective**: Understand how to use `ArrayList` to simulate a dynamic array that can expand based on runtime decisions.
65+
66+
**Task**:
67+
68+
- Create an `ArrayList` to store strings.
69+
- Simulate receiving an unknown number of string inputs from a user until "stop" is entered.
70+
- Store each input in the `ArrayList` and then print the entire list once "stop" is entered.
71+
72+
**Expected Output**: Output all user inputs stored in the `ArrayList` after the user stops entering data.
73+
74+
---
75+
76+
## Exercise 5: Merging and Deduplicating ArrayLists
77+
78+
**Objective**: Learn to merge two `ArrayLists` and remove duplicate items effectively.
79+
80+
**Task**:
81+
82+
- Create two `ArrayLists` of strings, each initialized with some predefined values, including some duplicates across the lists.
83+
- Merge the two lists into a new list that contains only unique elements, preserving the order.
84+
- Use a `HashSet` or `LinkedHashSet` to help with deduplication if necessary.
85+
86+
**Expected Output**: A single merged `ArrayList` without duplicates, printed to the console.
87+
88+
---
89+
90+
## Exercise 6: `ArrayList` as a Stack
91+
92+
**Objective**: Emulate stack behavior using an `ArrayList` to understand how it can be adapted for different data structure behaviors.
5393

5494
**Task**:
5595

56-
Create a class `Product` that implements the `Comparable` interface.
57-
A `Product` object has two properties:
58-
- `String productId`
59-
- `double price`
96+
- Use an `ArrayList` to implement a basic stack with operations: push, pop, and peek.
97+
- Ensure your implementation handles underflow (popping from an empty stack) gracefully.
98+
- Push a series of integers onto the stack, then pop several items, and peek at the top item, printing the results at each step.
6099

61-
The `compareTo` method should sort products based on their price in ascending order.
100+
**Expected Output**: Show the contents of the stack after each operation and the result of peeking or popping items.
101+
102+
---
62103

63-
- Override the `equals` method in the `Product` class to ensure it is consistent with the `compareTo` method (i.e., two `Product` objects are equal if their `productId` is the same).
64-
- In your `main` method, create a `TreeSet` of `Product` objects and attempt to add duplicate products based on the `productId` to understand how the `equals` method is used in collection operations.
65-
- Iterate over the `TreeSet` and print out the details of each product to observe the effect of a consistent `equals` method.
104+
## Exercise 7: Random Access vs. Iterative Access in `ArrayList`
105+
106+
**Objective**: Compare the performance of random access and sequential iterative access in an `ArrayList`.
107+
108+
**Task**:
66109

67-
> **Why `TreeSet` instead of `HashSet`?**
68-
>
69-
> The `HashSet` does not maintain elements in sorted order; it's a collection designed for fast access and uniqueness checks without regard to the order of elements.
70-
> The sorting behavior you're expecting (i.e., seeing `Product` instances in a particular order based on their `productId` or `price`) won't be achieved with a `HashSet`.
71-
>
72-
> `TreeSet` is a sorted collection that uses the natural ordering of its elements (defined by the `Comparable` implementation) or a `Comparator` provided at set creation time.
110+
- Fill an `ArrayList` with a large number of integers.
111+
- Measure and compare the time taken to access all elements randomly versus accessing them sequentially.
112+
- Use `System.nanoTime()` to measure elapsed time for each operation.
73113

74-
**Expected Output**: The `TreeSet` should eliminate duplicate products based on the `productId`, demonstrating the importance of having a consistent `equals` method with `compareTo`.
114+
**Expected Output**: Print the time taken for random access and sequential access, highlighting the differences.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
package collections.arraylist.exercises;
2+
3+
public class BasicArrayListOperations {
4+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package collections.arraylist.exercises;
2+
3+
import java.util.ArrayList;
4+
import java.util.Scanner;
5+
6+
public class ImplementingDynamicArray {
7+
8+
public static void main(String[] args) {
9+
Scanner scanner = new Scanner(System.in);
10+
ArrayList<String> inputs = new ArrayList<>();
11+
12+
System.out.println("Enter strings to store in the dynamic array. Type 'stop' to finish.");
13+
14+
while (true) {
15+
String input = scanner.nextLine();
16+
if ("stop".equalsIgnoreCase(input)) {
17+
break; // Exit the loop if user enters "stop"
18+
}
19+
inputs.add(input);
20+
}
21+
22+
scanner.close(); // Close the scanner
23+
24+
// Print all stored inputs
25+
System.out.println("You entered the following strings:");
26+
for (String str : inputs) {
27+
System.out.println(str);
28+
}
29+
}
30+
31+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package collections.arraylist.exercises;
2+
3+
import java.util.ArrayList;
4+
import java.util.LinkedHashSet;
5+
import java.util.List;
6+
import java.util.Set;
7+
8+
public class MergingAndDeduplicatingArrayLists {
9+
10+
public static void main(String[] args) {
11+
// Create two ArrayLists with some predefined values and duplicates across the lists
12+
List<String> list1 = new ArrayList<>(List.of("apple", "banana", "cherry"));
13+
List<String> list2 = new ArrayList<>(List.of("banana", "dragonfruit", "apple", "elderberry"));
14+
15+
// Merge the two lists into a new list
16+
List<String> mergedList = new ArrayList<>(list1);
17+
mergedList.addAll(list2);
18+
19+
// Use a LinkedHashSet to remove duplicates and preserve order
20+
Set<String> set = new LinkedHashSet<>(mergedList);
21+
List<String> deduplicatedList = new ArrayList<>(set);
22+
23+
// Print the deduplicated list
24+
System.out.println("Merged and Deduplicated List:");
25+
deduplicatedList.forEach(System.out::println);
26+
}
27+
28+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package collections.arraylist.exercises;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.Random;
6+
7+
public class RandomAccessVsIterativeAccess {
8+
9+
public static void main(String[] args) {
10+
final int SIZE = 100000; // Number of integers to be added to the ArrayList
11+
List<Integer> numbers = new ArrayList<>(SIZE);
12+
Random random = new Random();
13+
14+
// Filling the ArrayList with random integers
15+
for (int i = 0; i < SIZE; i++) {
16+
numbers.add(random.nextInt());
17+
}
18+
19+
// Sequential access
20+
long startTimeSequential = System.nanoTime();
21+
for (int i = 0; i < SIZE; i++) {
22+
int num = numbers.get(i); // Sequential access
23+
}
24+
long endTimeSequential = System.nanoTime();
25+
long durationSequential = endTimeSequential - startTimeSequential;
26+
27+
// Random access
28+
long startTimeRandom = System.nanoTime();
29+
for (int i = 0; i < SIZE; i++) {
30+
int index = random.nextInt(SIZE); // Generate a random index to access
31+
int num = numbers.get(index); // Random access
32+
}
33+
long endTimeRandom = System.nanoTime();
34+
long durationRandom = endTimeRandom - startTimeRandom;
35+
36+
// Output the results
37+
System.out.println("Time taken for sequential access: " + durationSequential + " nanoseconds");
38+
System.out.println("Time taken for random access: " + durationRandom + " nanoseconds");
39+
40+
// Highlighting the difference
41+
if (durationSequential < durationRandom) {
42+
System.out.println("Sequential access was faster by " + (durationRandom - durationSequential) + " nanoseconds.");
43+
} else {
44+
System.out.println("Random access was faster by " + (durationSequential - durationRandom) + " nanoseconds.");
45+
}
46+
}
47+
48+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package collections.arraylist.exercises;
2+
3+
public class SimplifiedStackUsingArrayList<T> {
4+
5+
private Object[] array; // Using Object array to store any type of items
6+
private int size = 0; // Current number of items in the stack
7+
private int capacity; // Maximum capacity of the stack
8+
9+
public SimplifiedStackUsingArrayList(int capacity) {
10+
this.capacity = capacity;
11+
array = new Object[capacity];
12+
}
13+
14+
public void push(T item) {
15+
if (size == capacity) {
16+
throw new StackOverflowError("Stack is full");
17+
}
18+
array[size++] = item;
19+
}
20+
21+
@SuppressWarnings("unchecked")
22+
public T pop() {
23+
if (size == 0) {
24+
throw new IllegalStateException("Stack is empty");
25+
}
26+
return (T) array[--size];
27+
}
28+
29+
@SuppressWarnings("unchecked")
30+
public T peek() {
31+
if (size == 0) {
32+
throw new IllegalStateException("Stack is empty");
33+
}
34+
return (T) array[size - 1];
35+
}
36+
37+
public boolean isEmpty() {
38+
return size == 0;
39+
}
40+
41+
public static void main(String[] args) {
42+
SimplifiedStackUsingArrayList<Integer> stack = new SimplifiedStackUsingArrayList<>(10);
43+
44+
stack.push(1);
45+
stack.push(2);
46+
stack.push(3);
47+
48+
System.out.println("Top element (peek): " + stack.peek()); // Should print 3
49+
System.out.println("Pop element: " + stack.pop()); // Should remove and print 3
50+
System.out.println("Next top element (peek): " + stack.peek()); // Should print 2
51+
52+
// Demonstrate pushing beyond capacity
53+
try {
54+
for (int i = 0; i < 10; i++) {
55+
stack.push(i);
56+
}
57+
} catch (StackOverflowError e) {
58+
System.out.println(e.getMessage());
59+
}
60+
}
61+
62+
}
63+

src/main/java/collections/arraylist/Product.java renamed to src/main/java/collections/treeset/ConsistencyWithEqualsMethod.java

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1-
package collections.arraylist;
1+
package collections.treeset;
2+
3+
import lombok.Getter;
24

35
import java.util.Objects;
46
import java.util.Set;
57
import java.util.TreeSet;
68

7-
public class Product implements Comparable<Product> {
9+
@Getter
10+
class Product implements Comparable<Product> {
811

912
private final String productId;
1013
private final double price;
@@ -21,8 +24,8 @@ public int compareTo(Product product) {
2124

2225
@Override
2326
public boolean equals(Object obj) {
24-
if (this == obj) return true;
25-
if (obj == null || getClass() != obj.getClass()) return false;
27+
if (this == obj) { return true; }
28+
if (obj == null || getClass() != obj.getClass()) { return false; }
2629
Product product = (Product) obj;
2730
return Objects.equals(this.productId, product.productId);
2831
}
@@ -32,9 +35,14 @@ public int hashCode() {
3235
return Objects.hash(this.productId, this.price);
3336
}
3437

38+
}
39+
40+
public class ConsistencyWithEqualsMethod {
41+
3542
public static void main(String[] args) {
3643
Product x = new Product("1234", 123.45);
3744
Product y = new Product("1234", 123.45);
45+
if ((x.compareTo(y) == 0) != (x.equals(y))) { throw new AssertionError("Condition should evaluate to true"); }
3846
System.out.println((x.compareTo(y) == 0) == (x.equals(y)));
3947

4048
TreeSet<Product> products = new TreeSet<>(Set.of(
@@ -43,7 +51,7 @@ public static void main(String[] args) {
4351
new Product("2136", 123.45),
4452
new Product("2136", 321.45)
4553
));
46-
products.forEach(product -> System.out.println("Product ID: " + product.productId + "; Price: " + product.price));
54+
products.forEach(product -> System.out.println("Product ID: " + product.getProductId() + "; Price: " + product.getPrice()));
4755
}
4856

4957
}

0 commit comments

Comments
 (0)