Unit 7 - ArrayList
Unit 7.1
Popcorn Hack 1
import java.util.ArrayList;
ArrayList<String> awesomeword = new ArrayList();
ArrayList<Int> coolnumbers = new ArrayList();
ArrayList<Boolean> truefalse = new ArrayList();
When using ArrayLists, you need to specify the type in the <>. For the coolnumbers
, there is Int
which isn’t a valid type. You need to write Integer
instead. For all of the above, you need to write new ArrayList()<variable type>();
, not just new ArrayList();
.
import java.util.ArrayList;
// fixed code
ArrayList<String> awesomeword = new ArrayList<String>();
ArrayList<Integer> coolnumbers = new ArrayList<Integer>();
ArrayList<Boolean> truefalse = new ArrayList<Boolean>();
Popcorn Hack 2
Create 2 ArrayLists, one with an integer type called “sritestgrades” and other string type called “srihobbies
import java.util.ArrayList;
ArrayList<?> sritestgrades = new ArrayList<>(); // change the question marks
ArrayList<?> srishobbies = new ArrayList<>();
sritestgrades.add(45);
sritestgrades.add(32);
sritestgrades.add(1);
sritestgrades.add(90);
sritestgrades.add(74);
srishobbies.add("watching netflix");
srishobbies.add("sleeping");
srishobbies.add("coding");
srishobbies.add("annoying saathvik");
// Printing the values
System.out.println("Sri's Test Grades are: " + sritestgrades);
System.out.println("Sri's Hobbies are: " + srishobbies);
// intended output:
// Sri's Test Grades are: [45, 32, 1, 90, 74]
// Sri's Hobbies are: [watching netflix, sleeping, coding, annoying saathvik]
import java.util.ArrayList;
ArrayList<Integer> sritestgrades = new ArrayList<>(); // using Integer for test grades
ArrayList<String> srishobbies = new ArrayList<>(); // using String for hobbies
// add the grades
sritestgrades.add(45);
sritestgrades.add(32);
sritestgrades.add(1);
sritestgrades.add(90);
sritestgrades.add(74);
// adding hobbies
srishobbies.add("watching netflix");
srishobbies.add("sleeping");
srishobbies.add("coding");
srishobbies.add("annoying saathvik");
// outputting the values
System.out.println("Sri's Test Grades are: " + sritestgrades);
System.out.println("Sri's Hobbies are: " + srishobbies);
Sri's Test Grades are: [45, 32, 1, 90, 74]
Sri's Hobbies are: [watching netflix, sleeping, coding, annoying saathvik]
Unit 7.2
Popcorn Hack 1
The learning objective is that “Students will be able to represent collections of related object reference data using ArrayList objects.” What does this mean to you?
The learning objective, “Students will be able to represent collections of related object reference data using ArrayList
objects,” emphasizes teaching how to manage groups of related objects effectively through the use of ArrayList
. Here’s what this means:
- Understanding Object Reference Data:
- Each element in an
ArrayList
refers to an object or a reference type (likeInteger
,String
, or custom objects). It’s about storing references to objects rather than the objects themselves. - For example, an
ArrayList<String>
stores references toString
objects, not the actualString
values themselves.
- Each element in an
- Collections of Related Data:
- We will learn to use
ArrayList
to represent a group of related data. Ex: making anArrayList<Student>
where each element refers to aStudent
object. - This objective highlights organizing and managing collections of related data efficiently using the flexible features of an
ArrayList
.
- We will learn to use
- Key Features of
ArrayList
:- Dynamic sizing: Unlike arrays,
ArrayList
can grow and shrink as needed. - Methods like
add()
,remove()
,set()
, andget()
allow manipulation of the list. - Learn how to apply these methods to manage collections of data in real-world applications.
- Dynamic sizing: Unlike arrays,
- Practical Application:
- Use
ArrayList
to represent data structures such as lists of names, grades, or even more complex entities like books in a library or items in a shopping cart. - This teaches how to store, retrieve, and modify collections of data using object-oriented programming concepts.
- Use
In summary, the goal is to we are comfortable using ArrayList
to represent and manipulate collections of objects, preparing us for scenarios where managing dynamic lists of data is essential.
Popcorn Hack 2
Look back at Size of the ArrayList. What does the code output and why?
size()
returns the number of elements in the array list. Since no elements were added, the size is 0.
Popcorn Hack 3
Look back at Adding items to an ArrayList. What does the code output and why? What type of function is void, and what will be the return value?
add() adds a specific element at a specific index. This will move the previous item to the right. So when adding the new element, 2.0 and 3.0 are shifted and 4.0 is inserted to get [1.0, 4.0, 2.0, 3.0]
.
A function defined as void returns no value. It can perform an action, but it returns nothing. For add(), it performs the action of inserting the value but it won’t return anything.
Popcorn Hack 4
Look back at Example 1. What two lines did we remove? Why?
ArrayList<String>
only holds strings, so the lines h.add(26.2);
and h.add(false);
won’t work since they are double and booleans, respectively. If I left the lines in, I get a type mismatch error. You need to remove those lines to get no errors.
Popcorn Hack 5
If an ArrayList is being used as a parameter, what are the only two methods I can use from it? What would happen if I tried to use any other methods?
You can only use get(int index)
(retrieve element at a specified index) and size()
(returns number of elements in ArrayList). If I use add(), remove(), clear(), etc, I will modify it. If arraylist is passed as a parameter and is immutable/read-only, I can’t modify it. If there’s no restructions, I can use those other methods.
Popcorn Hack 6
Using the Hack Helper, write code that will:
- Add 2 items to the list.
- Remove an item from the list anywhere of the user’s choice.
- Replace am item anywhere in the list of the user’s choice.
- Get the first and last element of the list, no matter the length.
- Return the items added, removed, replaced, and the list’s size, in one string.
import java.util.ArrayList;
public class ArrayListMethodsExample {
// method to manipulate the list
private String manipulateList(int toAdd1, int toAdd2, int toRemoveIndex, int toReplaceIndex, int newValue) {
ArrayList<Integer> arr = new ArrayList<>();
// add two items to the list
arr.add(toAdd1);
arr.add(toAdd2);
// remove an item at the index of the user’s choice
int removedItem = arr.remove(toRemoveIndex);
// replace an item at the index of the user’s choice
int replacedItem = arr.set(toReplaceIndex, newValue); // returns the replaced item
// get the first and last element of the list
int firstElement = arr.get(0);
int lastElement = arr.get(arr.size() - 1);
// return details as a string
return "Items added: " + toAdd1 + ", " + toAdd2 +
"\nItem removed: " + removedItem +
"\nItem replaced: " + replacedItem + " with " + newValue +
"\nFirst item: " + firstElement +
"\nLast item: " + lastElement +
"\nList size: " + arr.size();
}
public static void main(String[] args) {
ArrayListMethodsExample example = new ArrayListMethodsExample();
// example use case: adding, removing, and replacing based on user input
String output = example.manipulateList(5, 10, 0, 0, 20);
// print the output
System.out.println(output);
}
}
Unit 7.3
Popcorn Hack 1
import java.util.ArrayList;
public class SumArrayList {
public static void main(String[] args) {
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(50);
myList.add(30);
myList.add(20);
// variable to store the sum
int sum = 0;
// loop through the list and calculate the sum
for (Integer value : myList) {
sum += value; // Add each value to sum
}
// print out the sum of all elements
System.out.println("Sum of elements: " + sum);
}
}
Popcorn Hack 2
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// use Double for the grades ArrayList, as it contains decimal values
ArrayList<Double> grades = new ArrayList<>();
grades.add(68.9);
grades.add(71.0); // using 71.0 to keep all values as Double
grades.add(100.0);
grades.add(80.0);
// iterate in reverse to avoid skipping elements when removing
for (int i = grades.size() - 1; i >= 0; i--) {
if (grades.get(i) < 70) {
// remove the grade if it's below 70
grades.remove(i);
}
}
// print the updated grades list
System.out.println(grades);
}
}
Unit 7.4
public class ArrayListExample {
private double findMax(double[] values) {
double max = values[0];
for (int index = 1; index < values.length; index++) {
if (values[index] > max) {
max = values[index];
}
}
return max;
}
public static void main(String[] args) {
double[] nums = {1.0, 3.0, 2.0, 2.0, 1.0, 5.0, 2.421, 4.0, 61.0, 2.0, 51.0, 120.0};
ArrayListExample example = new ArrayListExample();
double max = example.findMax(nums);
System.out.println("Maximum value: " + max);
}
}
ArrayListExample.main(null);
public class ArrayListExample {
private double findMax(ArrayList<Double> values) {
double max = values.get(0);
for (int index = 1; index < values.size(); index++) {
if (values.get(index) > max) {
max = values.get(index);
}
}
return max;
}
public static void main(String[] args) {
ArrayList<Double> nums = new ArrayList<>();
nums.add(41.0);
nums.add(384.0);
nums.add(2.0);
nums.add(25.0);
nums.add(11.0);
nums.add(120.0);
nums.add(21.0);
nums.add(4.03);
nums.add(6.0);
nums.add(2.230);
nums.add(25.01);
nums.add(10.420);
ArrayListExample example = new ArrayListExample();
double max = example.findMax(nums);
System.out.println("Maximum value: " + max);
}
}
ArrayListExample.main(null);
- What is the difference between the two examples above. Which one is better and why?
- The first example uses a primitive array (
double[]
) to store values. Access to elements is viavalues[index]
since arrays allow direct index access. It iterates through the array using its length property, values.length. The second example uses anArrayList<Double>
, which is a resizable data structure that belongs to Java’s Collection Framework. Access to elements is done viavalues.get(index)
. It iterates using thesize()
method to determine the number of elements. Array is better when: the size of the array is known and fixed in advance, as arrays are more memory-efficient. Also, access is faster due to direct indexing. ArrayList is better when: the list size may change dynamically (elements can be added/removed). There is more flexibility and built-in methods are required for convenience, though it is slightly less efficient due to method overhead. For which is better, it depends on the use case. If you’re dealing with a fixed-size collection of numbers, the first example (array) is more efficient. If you need flexibility in resizing the collection, the second example (ArrayList) is better.
- The first example uses a primitive array (
- Make your own algorithm using ArrayLists. Do not use the size and get methods, those are way too easy!
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class CustomArrayListReversal {
public void reverse(ArrayList<Double> values) {
// iterator to traverse the list
Iterator<Double> iterator = values.iterator();
// copy elements to another ArrayList in reverse order
ArrayList<Double> reversedList = new ArrayList<>();
while (iterator.hasNext()) {
reversedList.add(0, iterator.next()); // insert at the beginning of the new list
}
// clear the original list and copy the reversed elements back
values.clear();
values.addAll(reversedList);
}
public static void main(String[] args) {
ArrayList<Double> nums = new ArrayList<>();
nums.add(41.0);
nums.add(384.0);
nums.add(2.0);
nums.add(25.0);
nums.add(11.0);
nums.add(120.0);
nums.add(21.0);
nums.add(4.03);
CustomArrayListReversal example = new CustomArrayListReversal();
System.out.println("Original List: " + nums);
example.reverse(nums);
System.out.println("Reversed List: " + nums);
}
}
// This algorithm uses an Iterator to traverse the list without using size() or
// get(), and reverses the list by inserting elements at the start of a new list.
// This gives you a way to manipulate an ArrayList while avoiding the "easy" methods!
Unit 7.5
Popcorn Hack 1
What does each hop or jump represent? What code(look above) is used to achieve this?
Each hop represents a step. It goes through each variable and checks if it is the target. The code representing this is for for loop. It loops through the array and checks if we found the right one. If not, it continues. It does this for every element.
HW
Imagine you’re an online E-store that sells video games. Use linear searching to help Aidan find if the game, Grand Theft Auto V, is offered in the E-store. If it is, tell him the price. If it isn’t, tell him where he can find it
import java.util.ArrayList;
public class SearchString {
public static void main(String[] args) {
ArrayList<String> videoGames = new ArrayList<>();
videoGames.add("Roblox");
videoGames.add("Fortnite");
videoGames.add("Valorant");
videoGames.add("Apex Legends");
videoGames.add("GTA V");
// the game Aidan is searching for
String gameToSearch = "GTA V";
// perform linear search
boolean found = false;
double price = 0.0;
// hardcoded price for GTA V
if (gameToSearch.equals("GTA V")) {
price = 29.99; // set a price for GTA V
}
for (String game : videoGames) {
if (game.equalsIgnoreCase(gameToSearch)) {
found = true;
break;
}
}
// check the result of the search
if (found) {
System.out.println("Yes, " + gameToSearch + " is offered in the E-store. The price is $" + price + ".");
} else {
System.out.println("Sorry, " + gameToSearch + " is not available in the E-store. You can find it at a local game store or online retailers.");
}
}
}
SearchString.main(null);
Yes, GTA V is offered in the E-store. The price is $29.99.
Unit 7.6
You’re a teacher for a computer science class at Rancho Bernardo. You have a list of all the grades of the students in your class but its hard to see who has the highest and lowest grade. Use either insertion sort or selection sort to sort the ArrayList so the grades are easy to see.
I added both sorting methods so the user can choose.
import java.util.ArrayList;
public class Sorting {
// insertion Sort Algorithm
public static void insertionSort(ArrayList<Integer> elements) {
for (int i = 1; i < elements.size(); i++) {
int key = elements.get(i);
int j = i - 1;
// move elements of elements[0..i-1] that are greater than key
while (j >= 0 && elements.get(j) > key) {
elements.set(j + 1, elements.get(j));
j--;
}
elements.set(j + 1, key);
}
}
// selection Sort Algorithm
public static void selectionSort(ArrayList<Integer> elements) {
for (int i = 0; i < elements.size() - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < elements.size(); j++) {
if (elements.get(j) < elements.get(minIndex)) {
minIndex = j;
}
}
// swap the found minimum element with the first element
int temp = elements.get(minIndex);
elements.set(minIndex, elements.get(i));
elements.set(i, temp);
}
}
public static void main(String[] args) {
ArrayList<Integer> arr1 = new ArrayList<>();
arr1.add(85);
arr1.add(92);
arr1.add(76);
arr1.add(88);
arr1.add(67);
arr1.add(94);
arr1.add(73);
arr1.add(89);
arr1.add(91);
arr1.add(82);
arr1.add(78);
arr1.add(88);
arr1.add(95);
arr1.add(60);
arr1.add(84);
arr1.add(77);
arr1.add(91);
arr1.add(68);
arr1.add(97);
arr1.add(83);
// copy the original grades for sorting
ArrayList<Integer> insertionSortedGrades = new ArrayList<>(arr1);
ArrayList<Integer> selectionSortedGrades = new ArrayList<>(arr1);
// sort using Insertion Sort
insertionSort(insertionSortedGrades);
System.out.println("Grades sorted using Insertion Sort: " + insertionSortedGrades);
System.out.println("Highest grade: " + insertionSortedGrades.get(insertionSortedGrades.size() - 1));
System.out.println("Lowest grade: " + insertionSortedGrades.get(0));
// sort using Selection Sort
selectionSort(selectionSortedGrades);
System.out.println("\nGrades sorted using Selection Sort: " + selectionSortedGrades);
System.out.println("Highest grade: " + selectionSortedGrades.get(selectionSortedGrades.size() - 1));
System.out.println("Lowest grade: " + selectionSortedGrades.get(0));
}
}
Sorting.main(null);
Grades sorted using Insertion Sort: [60, 67, 68, 73, 76, 77, 78, 82, 83, 84, 85, 88, 88, 89, 91, 91, 92, 94, 95, 97]
Highest grade: 97
Lowest grade: 60
Grades sorted using Selection Sort: [60, 67, 68, 73, 76, 77, 78, 82, 83, 84, 85, 88, 88, 89, 91, 91, 92, 94, 95, 97]
Highest grade: 97
Lowest grade: 60