CSA Blog

Ian Wu

7.4 - Developing Algorithms Using ArrayLists

Home 7.1 Introduction 7.2 Methods 7.3 Traversing 7.4 Algorithms 7.5 Searching 7.6 Sorting 7.7 Ethical Issues

7.4 Developing Algorithms Using ArrayLists

Common Arraylist Methods:

  • size(): Returns the size of the arraylist as an Integer
  • add(object): Adds an object to the end of your ArrayList
  • void add(index, object): Addes an object to an index of your choice. Shifts the index of everything to the right by one and increases size by 1
  • get(index): Retrieves the object at the index specified
  • set(index, obj): Like void add, but instead of adding, it replaces the object that’s already in that index
  • remove(index): Removes the object at specified index
//size() & add(object)

ArrayList<Double> numbers = new ArrayList<>();
    numbers.add(1.0);
    numbers.add(2.0);
    numbers.add(3.0);

int size = numbers.size();

System.out.println(size);
3
//void add(index, object)
//get(index)
ArrayList<Double> numbers = new ArrayList<>();
    numbers.add(1.0);
    numbers.add(2.0);
    numbers.add(3.0);

System.out.println(numbers.get(2));

    numbers.add(2,4.0);

System.out.println(numbers.get(2));
System.out.println(numbers.get(3));
3.0
4.0
3.0
// set(index, obj)


ArrayList<Double> numbers = new ArrayList<>();
    numbers.add(1.0);
    numbers.add(2.0);
    numbers.add(3.0);

System.out.println(numbers.get(2));

    numbers.set(2,4.0);

System.out.println(numbers.get(2));

3.0
4.0
// remove(index)


ArrayList<Double> numbers = new ArrayList<>();
    numbers.add(1.0);
    numbers.add(2.0);
    numbers.add(3.0);
System.out.println(numbers.get(2));
    numbers.remove(2);

System.out.println(numbers.get(0));
System.out.println(numbers.get(1));
System.out.println(numbers.get(2));

//anybody know why we get an IndexOutofBoundsException eror?
3.0
1.0
2.0



---------------------------------------------------------------------------

java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 2

	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)

	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)

	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)

	at java.base/java.util.Objects.checkIndex(Objects.java:361)

	at java.base/java.util.ArrayList.get(ArrayList.java:427)

	at .(#38:1)

Here’s an example of a program using Arrays that finds the maximum value:

public class Main {
    public static void main(String[] args) {
        double[] values = {1, 2, 3, 4, 5};

        double maxValue = findMax(values);
        System.out.println("The maximum value is: " + maxValue);
    }

    private static 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;
    }
}
Main.main(null);
The maximum value is: 5.0

Now, how can we modify this to use an ArrayList?


public class Main {
    public static void main(String[] args) {
        ArrayList<Double> values = new ArrayList<>();
        values.add(1.2);
        values.add(3.4);
        values.add(2.6);
        values.add(4.9);
        values.add(0.8);

        double maxValue = findMax(values);
        System.out.println("The maximum value is: " + maxValue);
    }

    private static 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; 
    }
}
Main.main(null);

The maximum value is: 4.9

Homework:

(Paragraph Answer)

  1. What is the difference between the two examples above. Which one is better and why? One of the examples above uses arrays, while the other uses arrayLists. ArrayLists are more versatile than arrays, but since the algorithm does not modify the array, both work fine in this scenario.

(Code Answer)

  1. Make your own algorithm using ArrayLists that finds the sum of the elements in the ArrayList
public static int b(ArrayList<Double> c) {
    int e = 0;
    for (int d = 0; d < c.size(); d++) {
        e += c.get(d);
    }
    return e;
}

ArrayList<Double> a = new ArrayList<>();
a.add(1.1);
a.add(2.2);
a.add(3.3);
a.add(7.9);
a.add(123.123081972386);
a.add(-1.218937812);
a.add(3.14159265);
a.add(43110.0);

int f = b(a);
System.out.println(f);
43247

7.3 - Traversing Arraylists

Home 7.1 Introduction 7.2 Methods 7.3 Traversing 7.4 Algorithms 7.5 Searching 7.6 Sorting 7.7 Ethical Issues

7.3 Traversing Arraylists

You can traverse through the elements in an ArrayList using loops. In order to traverse ArrayLists, we can use iterative statements, or loops. We can use For Each Loops, For Loops, and While Loops

The following code uses a For Each loop to traverse through the ArrayList.

//7.3.1: For Each Loop
ArrayList<Integer> myList = new ArrayList<Integer>();
        myList.add(50);
        myList.add(30);
        myList.add(20);
        for (Integer value : myList)
        {
            System.out.println(value);
        }
50
30
20

Popcorn Hack #1:

Modify the code above so that it prints out the sum of all the elements in the list.

//7.3.1: For Each Loop
ArrayList<Integer> myList = new ArrayList<Integer>();
int sum = 0;
myList.add(50);
myList.add(30);
myList.add(20);
for (Integer value : myList)
{
    sum += value;
}
System.out.println(sum);
100

The problem with For Each loops is that you can’t modify the ArrayList. To do that, you will need to use another type of loop. If you attempt to modify the ArrayList, you will get a ConcurrentModificationException error.

ConcurrentModificationException Error:

  • Happens when you try to modify the structure of an ArrayList using a For Each loop.

Think about it this way: Imagine you are standing in a line at the store and then somebody cuts the line. The order of the line has changed. The store doesn’t want people cutting the line becaues it changes the order and creates confusion. So, it throws out a ConcurrentModificationError to alert you that something is wrong and that you shouldn’t do it.

It’s the same for For Each Loops in Java - You can’t add or remove elements because it changes the structure of the loop.

image

Common mistakes with For Each Loops:

  1. Make sure that the data type of your variable is the same as the data type of the ArrayList
  2. Don’t try to modify the ArrayList!!!!!! I can’t stress this enough

image

For Loops

Here’s how to traverse through an arraylist using a For Loop. The following code will give you an IndexOutOfBounds error, do you know how to fix this error?

There are three major parts of a for loop:

  • Initialisation, this is where you declare the variable index

  • Boolean condition, this is where you declare the stop condition, when it’s true, it stops.

  • Update, this is the increment value, i++ is increment and i– is decrement

// 7.3.2 For Loops
ArrayList<Integer> myList = new ArrayList<Integer>();
        myList.add(50);
        myList.add(30);
        myList.add(20);
        for (int i = 0; i <= myList.size(); i++)  
        {
            System.out.println(myList.get(i));
        }

50
30
20



---------------------------------------------------------------------------

java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3

	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)

	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)

	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)

	at java.base/java.util.Objects.checkIndex(Objects.java:361)

	at java.base/java.util.ArrayList.get(ArrayList.java:427)

	at .(#46:1)

IndexOutOfBoundsException

  • This happens when the program is trying to fetch something that isn’t there. If we have the equals since in the for loop, it will try to fetch up to index 3 because thats the list size. When we remove the equals sign, it goes to whatever is <3, which is 2. So, it fetches up to index 2, meaning 3 elements.

Popcorn Hack 2:

Suppose we have an arraylist named grades, and we want to remove the entries that are lower than 70. Use a for loop to achieve this.

image

import java.util.ArrayList;
import java.util.List;

ArrayList<Double> grades = new ArrayList<Double>();
grades.add(6.6);
grades.add(71.8);
grades.add(100.2134);
grades.add(80.2139478123949123);
for(int i = 0; i<grades.size(); i++){
    if(grades.get(i)<70){
        grades.remove(i);
    }
}
System.out.println(grades);
[71.8, 100.2134, 80.2139478123949]

While Loops

Here is the final example of traversing through ArrayLists using while loops

ArrayList<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");

int index = 0;
while (index < fruits.size()) {
    System.out.println(fruits.get(index));
    index++;
}
apple
banana
orange

Unit 4 - HW Quiz

4.1 While Loop 4.2 For Loop 4.3 String Iteration 4.4 Nested Iteration Unit 4 HW Quiz

Unit 4 - Iteration:

  • This is the homework quiz for unit 4, iterations
  • 4 multiple choice questions
  • 2 programming hacks
  • 1 bonus programming hack (required to get above 0.9)

Question 1:

What does the following code print?

A. 5 6 7 8 9

B. 4 5 6 7 8 9 10 11 12

C. 3 5 7 9 11

D. 3 4 5 6 7 8 9 10 11 12

Click to reveal answer: D

Explain your answer. (explanation is graded not answer)

for (int i = 3; i <= 12; i++) {
   System.out.print(i + " ");
}

Answer: D The code iterates through all the numbers from 3 to 12 and prints out the index. It index starts at three, and therefore prints out three, then iterates by one and ends at 12. D is the only option that does this.

Bonus:

  • Explain the difference between using a variable like i inside a for loop, vs. using a variable that exists in the code itself for a while loop

Using a new variable ensures that the loop functions properly, because when a variable that exists in the code itself is used, things can change, as changing one part of the code results in alteration of another part that can have unexpected results.

Question 2:

How many times does the following method print a “*” ?

A. 9

B. 7

C. 8

D. 6

Click to reveal answer: C

Explain your answer. (explanation is graded not answer)

for (int i = 3; i < 11; i++) {
   System.out.print("*");
}

C. The code iterates beginning at 3 and ends at 11, index incrementing by one and printing out a * each time. It prints out the * 11-3 = 8 times.

Question 3:

What does the following code print?

A. -4 -3 -2 -1 0

B. -5 -4 -3 -2 -1

C. 5 4 3 2 1

Click to reveal answer: A

Explain your answer. (explanation is graded not answer)

int x = -5;
while (x < 0)
{
   x++;
   System.out.print(x + " ");
}

A. It prints out the index starting at -5 and is incremented by one each time. The increment is done before printing so it starts at -4.

Question 4:

What does the following code print?

A. 20

B. 21

C. 25

D. 30

Click to reveal answer: B

Explain your answer. (explanation is graded not answer)

int sum = 0;

for (int i = 1; i <= 5; i++) {
    if (i % 2 == 0) {
        sum += i * 2;
    } else {
        sum += i;
    }
}

System.out.println(sum);

This sums up the numbers from one two five but doubles the even numbers. 1 + 4 + 3 + 8 + 5 = 21.

Loops HW Hack

Easy Hack

  • Use a while loop to find the numbers from 1-50 that are divisible by 3 or 5, then store them into a list (make sure to print it out at the end)
  • Use a for loop to do the same thing detailed above
for (int i = 1; i < 51; i++) {
    if (i % 3 == 0) {
        System.out.println(i + " is divisible by 3");
    }
}

int j = 1;
while (j < 51) {
    if (j % 5 == 0) {
        System.out.println(j + " is divisible by 5");
    }
    j += 1;
}
3 is divisible by 3
6 is divisible by 3
9 is divisible by 3
12 is divisible by 3
15 is divisible by 3
18 is divisible by 3
21 is divisible by 3
24 is divisible by 3
27 is divisible by 3
30 is divisible by 3
33 is divisible by 3
36 is divisible by 3
39 is divisible by 3
42 is divisible by 3
45 is divisible by 3
48 is divisible by 3


5 is divisible by 5
10 is divisible by 5
15 is divisible by 5
20 is divisible by 5
25 is divisible by 5
30 is divisible by 5
35 is divisible by 5
40 is divisible by 5
45 is divisible by 5
50 is divisible by 5

Harder Hack

Palindromes are numbers that have the same value when reversed (ex: “123321” or “323”). Create a program that uses a while loop that outputs all palindromes in any given list.

Sample Input: test_list = [5672, 235, 5537, 6032, 317, 8460, 1672, 8104, 7770, 4442, 913, 2508, 1116, 9969, 9091, 522, 8756, 9527, 7968, 1520, 4444, 515, 2882, 6556, 595]

Sample Output: 4444, 515, 2882, 6556, 595

public static boolean isPalindrome(int number) {
    String str = Integer.toString(number);
    String reversedStr = new StringBuilder(str).reverse().toString();
    return str.equals(reversedStr);
}


int[] test_list = {5672, 235, 5537, 6032, 317, 8460, 1672, 8104, 7770, 4442, 913, 2508, 1116, 9969, 9091, 522, 8756, 9527, 7968, 1520, 4444, 515, 2882, 6556, 595};

for (int number : test_list) {
    if (isPalindrome(number)) {
        System.out.println(number + " is a palindrome.");
    }
}
4444 is a palindrome.
515 is a palindrome.
2882 is a palindrome.
6556 is a palindrome.
595 is a palindrome.

Bonus Hack (for above 0.9)

Use a for loop to output a spiral matrix with size n

Example:

Sample Input: n = 3

Output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]

static int n = 15;
static int[][] matrix = new int[n][n];
static int nextInt = 1;

int top = 0, bottom = n - 1, left = 0, right = n - 1;

while (nextInt <= n * n) {
    for (int col = left; col <= right && nextInt <= n * n; col++) {
        matrix[top][col] = nextInt++;
    }
    top++;

    for (int row = top; row <= bottom && nextInt <= n * n; row++) {
        matrix[row][right] = nextInt++;
    }
    right--;

    for (int col = right; col >= left && nextInt <= n * n; col--) {
        matrix[bottom][col] = nextInt++;
    }
    bottom--;

    for (int row = bottom; row >= top && nextInt <= n * n; row--) {
        matrix[row][left] = nextInt++;
    }
    left++;
}

for (int[] row : matrix) {
    for (int value : row) {
        System.out.print(value + "\t");
    }
    System.out.println();
}
1	2	3	4	5	6	7	8	9	10	11	12	13	14	15	
56	57	58	59	60	61	62	63	64	65	66	67	68	69	16	
55	104	105	106	107	108	109	110	111	112	113	114	115	70	17	
54	103	144	145	146	147	148	149	150	151	152	153	116	71	18	
53	102	143	176	177	178	179	180	181	182	183	154	117	72	19	
52	101	142	175	200	201	202	203	204	205	184	155	118	73	20	
51	100	141	174	199	216	217	218	219	206	185	156	119	74	21	
50	99	140	173	198	215	224	225	220	207	186	157	120	75	22	
49	98	139	172	197	214	223	222	221	208	187	158	121	76	23	
48	97	138	171	196	213	212	211	210	209	188	159	122	77	24	
47	96	137	170	195	194	193	192	191	190	189	160	123	78	25	
46	95	136	169	168	167	166	165	164	163	162	161	124	79	26	
45	94	135	134	133	132	131	130	129	128	127	126	125	80	27	
44	93	92	91	90	89	88	87	86	85	84	83	82	81	28	
43	42	41	40	39	38	37	36	35	34	33	32	31	30	29