1 | import java.util.ArrayList; |
2 | import java.util.Collections; |
3 | import java.util.Comparator; |
4 | import java.util.Scanner; |
5 | |
6 | |
7 | // See below for information on this class. |
8 | public class ArrayListExamples { |
9 | |
10 | public static void main(String[] args) { |
11 | // Example 1: Student Management System |
12 | studentManagementSystem(); |
13 | |
14 | System.out.println("\n-----------------------------------\n"); |
15 | |
16 | // Example 2: Shopping Cart Implementation |
17 | shoppingCartExample(); |
18 | } |
19 | |
20 | /** |
21 | * Example 1: Student Management System |
22 | * Demonstrates adding, removing, searching, and sorting students |
23 | */ |
24 | public static void studentManagementSystem() { |
25 | System.out.println("STUDENT MANAGEMENT SYSTEM EXAMPLE"); |
26 | |
27 | // Create an ArrayList to store student names |
28 | ArrayList<String> students = new ArrayList<>(); |
29 | |
30 | // Add students to the list |
31 | students.add("Emma Johnson"); |
32 | students.add("Liam Smith"); |
33 | students.add("Olivia Williams"); |
34 | students.add("Noah Brown"); |
35 | students.add("Ava Jones"); |
36 | |
37 | // Display all students |
38 | System.out.println("Current Students:"); |
39 | for (int i = 0; i < students.size(); i++) { |
40 | System.out.println((i + 1) + ". " + students.get(i)); |
41 | } |
42 | |
43 | // Add a new student at a specific position (third position) |
44 | students.add(2, "Mason Davis"); |
45 | System.out.println("\nAfter adding Mason Davis at position 3:"); |
46 | displayList(students); |
47 | |
48 | // Check if a student exists |
49 | String searchName = "Ava Jones"; |
50 | if (students.contains(searchName)) { |
51 | System.out.println("\nFound student: " + searchName); |
52 | System.out.println("Position: " + (students.indexOf(searchName) + 1)); |
53 | } else { |
54 | System.out.println("\nStudent not found: " + searchName); |
55 | } |
56 | |
57 | // Remove a student |
58 | students.remove("Noah Brown"); |
59 | System.out.println("\nAfter removing Noah Brown:"); |
60 | displayList(students); |
61 | |
62 | // Sort students alphabetically |
63 | Collections.sort(students); |
64 | System.out.println("\nAlphabetically sorted students:"); |
65 | displayList(students); |
66 | |
67 | // Clear the entire list |
68 | students.clear(); |
69 | System.out.println("\nAfter clearing the list, size: " + students.size()); |
70 | } |
71 | |
72 | /** |
73 | * Example 2: Shopping Cart Implementation |
74 | * Demonstrates a more complex ArrayList with custom objects |
75 | */ |
76 | public static void shoppingCartExample() { |
77 | System.out.println("SHOPPING CART EXAMPLE"); |
78 | |
79 | // Create an ArrayList of items |
80 | ArrayList<CartItem> cart = new ArrayList<>(); |
81 | |
82 | // Add items to cart |
83 | cart.add(new CartItem("Laptop", 899.99, 1)); |
84 | cart.add(new CartItem("Mouse", 24.99, 1)); |
85 | cart.add(new CartItem("Keyboard", 59.99, 1)); |
86 | cart.add(new CartItem("USB Drive", 19.99, 2)); |
87 | |
88 | // Display cart contents |
89 | System.out.println("Shopping Cart Contents:"); |
90 | displayCart(cart); |
91 | |
92 | // Calculate and display total |
93 | double total = 0; |
94 | for (CartItem item : cart) { |
95 | total += item.getPrice() * item.getQuantity(); |
96 | } |
97 | System.out.printf("\nCart Total: $%.2f\n", total); |
98 | |
99 | // Update quantity of an item |
100 | for (CartItem item : cart) { |
101 | if (item.getName().equals("USB Drive")) { |
102 | item.setQuantity(3); |
103 | System.out.println("\nUpdated USB Drive quantity to 3"); |
104 | break; |
105 | } |
106 | } |
107 | |
108 | // Display updated cart and total |
109 | System.out.println("\nUpdated Shopping Cart:"); |
110 | displayCart(cart); |
111 | |
112 | // Recalculate total |
113 | total = 0; |
114 | for (CartItem item : cart) { |
115 | total += item.getPrice() * item.getQuantity(); |
116 | } |
117 | System.out.printf("\nNew Cart Total: $%.2f\n", total); |
118 | |
119 | // Sort by price (using Comparator) |
120 | // Look BELOW for some explanation of this... |
121 | Collections.sort(cart, new Comparator<CartItem>() { |
122 | @Override |
123 | public int compare(CartItem item1, CartItem item2) { |
124 | return Double.compare(item1.getPrice(), item2.getPrice()); |
125 | } |
126 | }); |
127 | |
128 | System.out.println("\nCart Items Sorted by Price (Low to High):"); |
129 | displayCart(cart); |
130 | |
131 | // Remove an item |
132 | cart.removeIf(item -> item.getName().equals("Mouse")); |
133 | System.out.println("\nAfter removing Mouse:"); |
134 | displayCart(cart); |
135 | } |
136 | |
137 | // Helper method to display a list of strings |
138 | private static void displayList(ArrayList<String> list) { |
139 | for (int i = 0; i < list.size(); i++) { |
140 | System.out.println((i + 1) + ". " + list.get(i)); |
141 | } |
142 | } |
143 | |
144 | // Helper method to display cart items |
145 | private static void displayCart(ArrayList<CartItem> cart) { |
146 | for (int i = 0; i < cart.size(); i++) { |
147 | CartItem item = cart.get(i); |
148 | System.out.printf("%d. %-10s $%.2f x %d = $%.2f\n", |
149 | i + 1, |
150 | item.getName(), |
151 | item.getPrice(), |
152 | item.getQuantity(), |
153 | item.getPrice() * item.getQuantity()); |
154 | } |
155 | } |
156 | } |
157 | |
158 | /** |
159 | * Class representing an item in a shopping cart |
160 | */ |
161 | class CartItem { |
162 | private String name; |
163 | private double price; |
164 | private int quantity; |
165 | |
166 | public CartItem(String name, double price, int quantity) { |
167 | this.name = name; |
168 | this.price = price; |
169 | this.quantity = quantity; |
170 | } |
171 | |
172 | public String getName() { |
173 | return name; |
174 | } |
175 | |
176 | public double getPrice() { |
177 | return price; |
178 | } |
179 | |
180 | public int getQuantity() { |
181 | return quantity; |
182 | } |
183 | |
184 | public void setQuantity(int quantity) { |
185 | this.quantity = quantity; |
186 | } |
187 | } |
Explaining the Sort thing in the Cart
This code is sorting a list of shopping cart items by price using Java's Collections.sort method. Let me break it down:
Collections.sort(cart, new Comparator<CartItem>() {
@Override
public int compare(CartItem item1, CartItem item2) {
return Double.compare(item1.getPrice(), item2.getPrice());
}
});
Here's what each part does:
-
Collections.sort(cart, ...)
- This is calling Java's built-in sort method on a collection named "cart" which contains CartItem objects. -
new Comparator<CartItem>() { ... }
- This creates an anonymous inner class that implements the Comparator interface specifically for CartItem objects. The Comparator defines how two CartItems should be compared. -
@Override public int compare(CartItem item1, CartItem item2)
- This overrides the compare method from the Comparator interface. It takes two CartItem objects and returns an integer that indicates their relative ordering. -
return Double.compare(item1.getPrice(), item2.getPrice());
- This compares the prices of the two cart items using Double.compare (which handles special cases like NaN values properly). It will return:- A negative value if item1's price is less than item2's price
- Zero if the prices are equal
- A positive value if item1's price is greater than item2's price
After this code executes, the "cart" collection will be sorted in ascending order by price, with the cheapest items first and the most expensive items last.
I'll share some practical examples of using the ArrayList class in Java, focusing on different real-world scenarios.
These examples demonstrate two common use cases for ArrayLists in Java:
Example 1: Student Management System
The first example shows how to use an ArrayList to manage a list of students, demonstrating:
- Adding students to the list
- Inserting a student at a specific position
- Searching for students
- Removing students
- Sorting the list alphabetically
- Clearing the entire list
Example 2: Shopping Cart Implementation
The second example is more complex, using an ArrayList to manage a shopping cart with custom objects:
- Creating and storing custom objects (CartItem class)
- Calculating totals from the items in the list
- Finding and updating specific items in the list
- Sorting items by price using a Comparator
- Removing items conditionally with the removeIf() method
These examples showcase the flexibility of ArrayList and how it can be used to manage both simple collections of strings and more complex collections of custom objects. Each example includes helpful methods for displaying the current state of the list, making it easier to understand how ArrayLists work in practice.