CodeGym /Java Course /Module 1. Java Syntax /Working with ArrayList, part 2

Working with ArrayList, part 2

Module 1. Java Syntax
Level 16 , Lesson 4
Available

1. Adding an element to the middle (or at the beginning) of a list

If we want to insert an element in the middle of the list, here's what happens inside the list.

Suppose we have a list of 11 elements:

Adding an element to the middle (or at the beginning) of a list

We want to insert the number 10,000 into the list at index 5. To do this, we just need to execute:

list.add(5, 10000);

Where list is an ArrayList variable. The add(int index, type value) method adds the value 10000 at position 5 in the list. Here's what happens in the add() method:

Step 1: All elements of the array, starting from the 5th position, will be shifted (copied) by 1 element toward the end of the array:

Adding an element to the middle (or at the beginning) of a list 1

Note that the elements in the 5th and 6th cell of the array are now the same.

Step 2: Write the value 10,000 into the 5th cell:

Adding an element to the middle (or at the beginning) of a list 2

Now the list contains all the elements of the array, and the fifth cell contains the number 10,000. Just what we wanted.


16
Task
New Java Syntax, level 16, lesson 4
Locked
Dividing by zero
Create a public static void divideByZero method that divides any number by zero, and display the result of the division. Wrap the divideByZero method call in a try-catch block. Display the exception stack trace using the exception.printStackTrace() method

2. Removing an element from a list

Removing an element from a list is similar to inserting it, but the process is reversed.

Let's remove the 3rd element from a list. To do this, we need to execute:

list.remove(3);

Here's what happens in the remove() method:

Step 1: The elements of the array, starting from the 4th position, will be shifted (copied) by 1 element toward the start of the array:

Removing an element from a list

Step 2: The value of the size variable will be decreased by 1.

Removing an element from a list 2

Please note there are some values colored gray at the end of the array. Technically, these are garbage. They need to be removed in order not to interfere with garbage collection.

Step 3: Cleaning up garbage

Removing an element from a list 3


16
Task
New Java Syntax, level 16, lesson 4
Locked
Countdown from 5 to 0
The loop counts down from 5 to 0. Add a delay using Thread.sleep(100); Wrap the sleep call in a try-catch block.

3. Practical examples of working with a list in Java

Let's write some examples of working with lists:

We'll list all the even numbers in the range from 1 to 20:

Code Notes
ArrayList<Integer> list = new ArrayList<Integer>();

for (int i = 1; i <= 20; i++)
   if (i%2 == 0)
      list.add(i);
Create a list object

Loop over all the indices 1 to 20
If the index is divisible by 2 without a remainder,
add it to the list

Now let's display all the elements of the list on the screen:

Code Notes
ArrayList<Integer> list = new ArrayList<Integer>();

for (int i = 1; i <= 20; i++)
   if (i%2 == 0)
      list.add(i);

for (int i = 0; i < list.size(); i++)
   System.out.println(list.get(i));
Create a list object
Loop over all the indices 1 to 20

If the number is divisible by 2 without a remainder,
add it to the list

Loop from zero to the size of the list
Display each element on the screen

Removing elements:

Now let's remove all elements that are divisible by 4. Note that after removing an element from the list, the positions of the remaining elements immediately change.

Code Notes
ArrayList<Integer> list = new ArrayList<Integer>();

for (int i = 1; i <= 20; i++)
   if (i%2 == 0)
      list.add(i);

for (int i = 0; i < list.size(); i++)
   if (list.get(i)%4 == 0)
   {
      list.remove(i);
      i--;
   }
Create a list object

Loop over all the indices 1 to 20
If the index is divisible by 2 without a remainder,
add it to the list

Loop from zero to the size of the list
If an element of the list is divisible by 4 without a remainder:

a) remove the element
b) decrease the i counter so we get the same index on the next iteration of the loop

Let's say you need to remove the last 3 elements from a list.

Here's how to do that incorrectly:

Code Notes
ArrayList<Integer> list = new ArrayList<Integer>();

for (int i = 1; i <= 20; i++)
   if (i%2 == 0)
      list.add(i);

int n = list.size();
list.remove(n - 3);
list.remove(n - 2);
list.remove(n - 1);
Create a list object

The list has 10 elements: 2, 4, 6, ... 20



n = 10
n - 3 = 7 (there are 9 elements left in the list)
n - 2 = 8 (there are 8 elements left in the list)
n - 1 = 9 (there are 7 elements left in the list)

After removing the 7th and 8th elements, only 8 elements will remain in the list. That means it won't be possible to delete the 9th element — an error will occur in the program.

Here's the right way to remove the elements:

Option 1 Option 2
int n = list.size();
list.remove(n - 3);
list.remove(n - 3);
list.remove(n - 3);
int n = list.size();
list.remove(n - 1);
list.remove(n - 2);
list.remove(n - 3);

The elements need to be removed either from the end or from another consistent location, since the elements get shifted by one after each removal operation.


16
Task
New Java Syntax, level 16, lesson 4
Locked
Throwing exceptions
There are four non-static methods: method1(), method2(), method3(), method4(). Using the throws keyword, make it so that method1() and method2() throw any checked exception, and method3() and method4() throw an unchecked exception.
16
Task
New Java Syntax, level 16, lesson 4
Locked
Vowels and consonants
Write a program that reads a string from the keyboard. The program should display two lines: 1. The first line contains only the vowels from the entered string. 2. The second contains only the consonants and punctuation marks from the entered string. The letters should be separated by a space, each
16
Task
New Java Syntax, level 16, lesson 4
Locked
A scary fairy tale
1. Once there were five classes: red riding hood, grandmother, pie, woodcutter, and wolf. 2. Each class has 2 fields: ArrayList killed and ArrayList ate. 3. The necessary objects have been created (hood, grandmother, ...). 4. Arrange the relationships correctly according to who ate and/or killed who
16
Task
New Java Syntax, level 16, lesson 4
Locked
Static modifiers are out of place
Rearrange the static modifiers so that the program compiles.
16
Task
New Java Syntax, level 16, lesson 4
Locked
List of number arrays
In the createList method: - create a list whose elements are arrays of numbers; - add to the list five array objects whose lengths are 5, 2, 4, 7, and 0, respectively; - fill the arrays with any data.
16
Task
New Java Syntax, level 16, lesson 4
Locked
Ten cats
There is a Cat class with a String variable name. Create a Map and add 10 cats represented by (name, Cat) pairs. Get a Set of all cats from the Map. Display the set on the screen (already implemented).
16
Task
New Java Syntax, level 16, lesson 4
Locked
Task about algorithms
The program reads words and numbers from the keyboard, adds them to a list, converts the list to an array, and then displays the array on the screen. Sort the array so that words appear in ascending order and numbers appear in descending order. Example input: Cherry 1 Bob 3 Apple 22 0 Watermelon E
Comments (10)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
m-troja Level 21, Warsaw, Poland
3 January 2024

 while(glasses.size() > 0)
        {
            glasses.remove(0);
        }
It's simplier, but was not accepted :D
Kubpal Level 15, Poland Expert
12 October 2024
In the task description is that you need delete last layer, not first one.
Parsa Level 62, Bangalore, India Expert
27 November 2023
Instead of

int n = list.size();
list.remove(n - 3);
list.remove(n - 3);
list.remove(n - 3);
You could simply write

list.remove(list.size()-1);
list.remove(list.size()-1);
list.remove(list.size()-1);
or loop over it three times.
Pekotski Level 16, Zurich, Switzerland
19 February 2024
Nice solution.
NonEuclid Level 20, Zurich, Switzerland
29 January 2023
In the remove example, you use list.remove(3) but it removes the last value of the array
tomtom6789 Level 32, University Place, United States
3 September 2023
I am having a same question
Emmelie Level 26, Göteborg, Sweden
26 September 2023
No, the 20 (in the table above) gets removed. The greyed 100 is a result of the shifting of elements and is garbage that gets removed by the garbage collector.
atb2199 Level 19, United Kingdom, United Kingdom
16 September 2022
I don't really understand. In the lesson, it tells us to remove an element it is simply list.remove(index); . Yet, in the solution to remove, it implements for loops... why?
Олег Байбула Level 32, Ukraine Expert
14 November 2022
indexOf method won't work, if there isn't the very object in the list. Remove "Pascal" from the list and you'll see.
Parsa Level 62, Bangalore, India Expert
27 November 2023
It's assuming you don't know the index, so you have to loop over it to find the index of Pascal and then remove it using its index.