POPCORN HACKS 7.1 & 7.2
Create an ArrayList of Strings with the following elements: “Apple”, “Banana”, “Cherry”, “Date”, “Elderberry”. Complete the following tasks using the ArrayList methods you’ve learned:
- Task 1: Print the size of the ArrayList.
- Task 2: Add a new element “Fig” to the end of the list.
- Task 3: Insert “Grape” at index 2.
- Task 4: Replace the element at index 4 with “Guava”.
- Task 5: Remove the element at index 1.
- Task 6: Retrieve and print the element at index 3.
At the end of each task, print the current state of the ArrayList to verify the result.
import java.util.ArrayList;
public class PopcornHacks {
public static void main(String[] args) {
// Initialize the ArrayList with elements
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Date");
fruits.add("Elderberry");
// Task 1: Print the size of the ArrayList
System.out.println("Task 1: Size of the ArrayList: " + fruits.size());
// Task 2: Add "Fig" to the end of the list
fruits.add("Fig");
System.out.println("Task 2: After adding Fig: " + fruits);
// Task 3: Insert "Grape" at index 2
fruits.add(2, "Grape");
System.out.println("Task 3: After inserting Grape at index 2: " + fruits);
// Task 4: Replace the element at index 4 with "Guava"
fruits.set(4, "Guava");
System.out.println("Task 4: After replacing element at index 4 with Guava: " + fruits);
// Task 5: Remove the element at index 1
fruits.remove(1);
System.out.println("Task 5: After removing element at index 1: " + fruits);
// Task 6: Retrieve and print the element at index 3
String element = fruits.get(3);
System.out.println("Task 6: Element at index 3: " + element);
}
}
PopcornHacks.main(null);
Task 1: Size of the ArrayList: 5
Task 2: After adding Fig: [Apple, Banana, Cherry, Date, Elderberry, Fig]
Task 3: After inserting Grape at index 2: [Apple, Banana, Grape, Cherry, Date, Elderberry, Fig]
Task 4: After replacing element at index 4 with Guava: [Apple, Banana, Grape, Cherry, Guava, Elderberry, Fig]
Task 5: After removing element at index 1: [Apple, Grape, Cherry, Guava, Elderberry, Fig]
Task 6: Element at index 3: Guava
Finish the code below so that it uses the findSum() method and it finds the sum of the numbers.
import java.util.ArrayList;
public class ArrayListHacks {
// Method to find the sum of the ArrayList elements
private int findSum(ArrayList<Integer> values) {
int sum = 0;
for (int value : values) {
sum += value;
}
return sum;
}
public static void main(String[] args) {
// Initialize ArrayList with numbers
ArrayList<Integer> nums = new ArrayList<>();
nums.add(0);
nums.add(1);
nums.add(2);
nums.add(3);
nums.add(5);
nums.add(8);
// Create an instance of ArrayListHacks and find the sum
ArrayListHacks hacks = new ArrayListHacks();
int sum = hacks.findSum(nums);
// Print the sum
System.out.println("Sum of the numbers: " + sum);
}
}
ArrayListHacks.main(null);
Sum of the numbers: 19
Problem: Sort the Ducks!
You have a list of ducks, and each duck has a name and weight. Your task is to sort these ducks by weight in ascending order.
Choose either Selection Sort or Insertion Sort to do the sorting.
Example:
Given this list:
- Duck A (4.5 kg)
- Duck B (2.1 kg)
- Duck C (5.0 kg)
- Duck D (1.9 kg)
After sorting, the output should be:
- Duck D (1.9 kg)
- Duck B (2.1 kg)
- Duck A (4.5 kg)
- Duck C (5.0 kg)
You can use this class for the ducks:
import java.util.ArrayList;
class DebugDuck implements Comparable<DebugDuck> {
String name;
double weight;
// Constructor to initialize the duck's name and weight
public DebugDuck(String name, double weight) {
this.name = name;
this.weight = weight;
}
// Compare ducks based on their weight
@Override
public int compareTo(DebugDuck other) {
return Double.compare(this.weight, other.weight);
}
// String representation for printing
@Override
public String toString() {
return name + " (" + weight + " kg)";
}
}
public class DuckSorter {
// Selection Sort implementation
public static void selectionSort(ArrayList<DebugDuck> ducks) {
int n = ducks.size();
for (int i = 0; i < n - 1; i++) {
// Find the minimum element in the unsorted part
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (ducks.get(j).compareTo(ducks.get(minIndex)) < 0) {
minIndex = j;
}
}
// Swap the found minimum element with the first unsorted element
DebugDuck temp = ducks.get(i);
ducks.set(i, ducks.get(minIndex));
ducks.set(minIndex, temp);
}
}
public static void main(String[] args) {
// Create an ArrayList of ducks
ArrayList<DebugDuck> ducks = new ArrayList<>();
ducks.add(new DebugDuck("Duck A", 4.5));
ducks.add(new DebugDuck("Duck B", 2.1));
ducks.add(new DebugDuck("Duck C", 5.0));
ducks.add(new DebugDuck("Duck D", 1.9));
// Print the list before sorting
System.out.println("Before sorting:");
for (DebugDuck duck : ducks) {
System.out.println(duck);
}
// Sort the ducks by weight
selectionSort(ducks);
// Print the list after sorting
System.out.println("\nAfter sorting:");
for (DebugDuck duck : ducks) {
System.out.println(duck);
}
}
}
DuckSorter.main(null);
Before sorting:
Duck A (4.5 kg)
Duck B (2.1 kg)
Duck C (5.0 kg)
Duck D (1.9 kg)
After sorting:
Duck D (1.9 kg)
Duck B (2.1 kg)
Duck A (4.5 kg)
Duck C (5.0 kg)
Mini Hack:
What can be used in place of the blank to ensure the users data is cleared?
ArrayList<String> userData = new ArrayList<>();
userData.add("John Doe");
userData.add("john@example.com");
// Once you're done using the data
userData.clear(); // Removes all entries from the list
userData = null; // Removes the reference to the ArrayList
ArrayList Coding Activity
Objective:
Students will create, manipulate, and sort an ArrayList
of integers.
Activity Outline:
1 Create an ArrayList:
- Task: Create an
ArrayList
of integers and add 5 elements of your choice. - Hint: Use the
ArrayList
class and the.add()
method to add elements.
import java.util.ArrayList;
import java.util.Collections;
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
System.out.println("Initial ArrayList: " + numbers);
Initial ArrayList: [10, 20, 30, 40, 50]
2 Modify an Element:
- Task: Change the second element (index 1) of the
ArrayList
to a new value (e.g., 100). - Hint: The
.set()
method allows you to update an element at a specific index.
// 2. Modify the second element (index 1) to a new value (e.g., 100)
numbers.set(1, 100);
System.out.println("After modifying the second element: " + numbers);
After modifying the second element: [10, 100, 30, 40, 50]
3 Remove an Element:
- Task: Remove the third element (index 2) from the
ArrayList
. - Hint: Use the
.remove()
method to delete an element by its index.
// 3. Remove the third element (index 2)
numbers.remove(2);
System.out.println("After removing the third element: " + numbers);
After removing the third element: [10, 100, 40, 50]
4 Search for an Element:
- Task: Check if a specific number (e.g., 30) is in the
ArrayList
and print a message based on whether it is found or not. - Hint: The
.contains()
method can be used to check for the presence of an element.
// 4. Search for an element (e.g., 30) in the ArrayList
if (numbers.contains(30)) {
System.out.println("30 is in the ArrayList.");
} else {
System.out.println("30 is not in the ArrayList.");
}
30 is not in the ArrayList.
5 Loop Through the ArrayList:
- Task: Use a
for
loop to print each element of theArrayList
. - Hint: You can use a traditional
for
loop or an enhancedfor
loop (for-each
) to iterate through the elements.
// 5. Loop through the ArrayList and print each element
System.out.println("Elements in the ArrayList:");
for (int num : numbers) {
System.out.println(num);
}
Elements in the ArrayList:
10
100
40
50
6 Sort the ArrayList:
- Task: Sort the
ArrayList
in ascending order. - Hint: Use
Collections.sort()
to sort theArrayList
.
// 6. Sort the ArrayList in ascending order
Collections.sort(numbers);
7 Print the Sorted ArrayList:
- Task: Print the sorted
ArrayList
to see the updated order of the elements. - Hint: Use
System.out.println()
to print the sorted list.
// 7. Print the sorted ArrayList
System.out.println("Sorted ArrayList: " + numbers);
Sorted ArrayList: [10, 40, 50, 100]