ArrayList

Java Syntax
Level 7 , Lesson 5
Available

"Here I am."

"Hi, Ellie!"

"Today we'll talk about an interesting topic. I'm going to tell you about the ArrayList class."

"A new class? Cool! What can it do?"

"Let me start with the back story. The only thing programmers dislike about arrays is that you can't change their size. What do you do if you need to add three more elements to an array that only has one free slot?"

"The only solution to this problem is to create very big arrays, in order to guarantee you have enough room for all the elements. However, this often means wasted memory. If an array usually contains three elements, but there is even the smallest chance that it might need to accommodate 100 elements, you have to create a 100-element array."

"So, what did programmers come up with?"

"They wrote the ArrayList class, which does the same thing as an Array, but it can change its size."

"Interesting move. How did they do that?"

"Every ArrayList object stores a regular array of elements. When you read elements from an ArrayList, it reads them from its inner array. When you write them to the ArrayList, it writes them to its inner array. Here, compare these columns:"

Array ArrayList
Create a container for elements
String[] list = new String[10];
ArrayList<String> list = new ArrayList<String>();
Get the number of elements
int n = list.length;
int n = list.size();
Get an element from an array/collection
String s = list[3];
String s = list.get(3);
Write an element into an array
list[3] = s;
list.set(3, s);

"So, why is the ArrayList better? As far as I can tell, the code is now longer."

"First, the ArrayList supports several additional operations that programmers have to perform all the time. An ordinary array doesn't support these operations. For example, inserting or deleting elements from the middle of an array without leaving holes."

"Second, the ability to change the size of the array. When you need to add one more element but the internal array doesn't have any free slots, here is what happens inside the ArrayList:

a) Another array is created that is 50% bigger than current inner array, plus one element.

b) All elements from the old array are copied into the new one.

c) The new array is saved as the ArrayList object's inner array. The old array is declared garbage (we simply stop storing a reference to it)."

Array ArrayList
Add an element at the end of the array
This action is not supported
list.add(s);
Add an element in the middle of the array
This action is not supported
list.add(15, s);
Add an element at the beginning of the array
This action is not supported
list.add(0, s);
Delete an element from the array
We could delete an element with list[3] = null. But this would leave a 'hole' in the array.
list.remove(3);
7
Task
New Java Syntax, level 7, lesson 5
Locked
The struggle for access
Before you is a program that displays information about a person. Unfortunately, it doesn't compile. Change the minimum required number of access modifiers in the Person class for the code to compile.

"How do we work with this ArrayList?"

"Actually, just as we do with an ordinary array. Look. Let's compare working with an ArrayList to working with an array. Suppose we need to 'read in 10 strings and display them on the screen in reversed order'."

"Look at this:

With an array
public static void main(String[] args)
{
Reader r = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(r);

// Read strings from the keyboard
String[] list = new String[10];
for (int i = 0; i < list.length; i++)
{
  String s = reader.readLine();
  list[i] = s;
}

// Display the contents of the array
for (int i = 0; i < list.length; i++)
{
  int j = list.length - i - 1;
  System.out.println( list[j] );
}
}
With an ArrayList
public static void main(String[] args)
{
Reader r = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(r);

// Read strings from the keyboard
ArrayList&ltString> list = new ArrayList&ltString>();
for (int i = 0; i < 10; i++)
{
  String s = reader.readLine();
  list.add(s);
}

// Display the contents of the collection
for (int i = 0; i < list.size(); i++)
{
  int j = list.size() - i - 1;
  System.out.println( list.get(j) );
}
}

I've used the same color to highlight similar actions in each column."

"On the one hand, everything is different. On the other, it's still the same."

"Right. Except that we don't use square brackets when working with an ArrayList. Instead, we use get, set and add methods."

"Yes, I gathered that much. Still, it looks very much the same."

7
Task
New Java Syntax, level 7, lesson 5
Locked
Analyzing arrays
This program should display information about the created array. But due to misplaced static modifiers, it won't compile. Correct these mistakes. Add the static modifier where it is needed.
Comments (52)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Rebecca Zee Level 10, New York, United States
14 July 2023
I don't get why it has that some of the operations are not supported for a regular array like inserting an element into a certain index and inserting an element in the middle. Unless they mean when the array is full these operations cannot be possible. Otherwise, it the array is partially filled, then these operations can be done. You just have to figure out a way to shift the elements to insert an element into the array.
Fadhil Radhian Level 18, Semarang, Indonesia
24 March 2023
the text colors are one of amazing teaching aspect of CodeGym that I rarely see elsewhere!
Aisuluu Zhumabaeva Level 16, Denver, United States
15 June 2021
For some reason new topic comes after Tasks belong to that topic and I cannot solve any of them because task come first. Why?
Ahmad Level 7, Detroit, United States
2 September 2021
The task on this page? All you have to do is type exactly what they typed.
Slawek Level 16, Wroclaw, Poland
31 January 2021
HI, // Read strings from the keyboard ArrayList<String> list = new ArrayList<String>(); for (int i = 0; i < 10; i++) { String s = reader.readLine(); list.add(s); } --> It doesn't work : error --> "no suitable method found for add(int) lista.add(i);" But if I use instead: list.add(reader.readLine()): it works
Jokeres Level 24, Budapest, Hungary
3 March 2021
it would work if you declare String s before the loop (maybe even if you declare it in the for() cycle rigth next to the int i) but as you can see String s does not have any use because you can just use the solution that you wrote at the end, and it's shorter, less variables are used so the code is better
Hisham Thabet Level 8, Lahj, Yemen
6 September 2021
Hi Slawek, Your code is right but you have one mistake when you declare the ArrayList<>.....just remove the word String from the end of declaration ArrayList like this : ArrayList<String> list = new ArrayList<>(); because the ArrayList on the right side is the constructor for the ArrayList class and it is enough to set data type in left side. Good luck
Chang You Level 47, Santa Rosa, United States
22 December 2020
What does "leave a 'hole' in the array" mean?
Andrei Level 41
8 January 2021
It means that if you remove an element let's say from the middle of the array then that memory space remains empty and could falsely indicate the presence of a value. Btw, how are you already lvl 41 lol ?
Cristian Level 13, Ploiesti, Romania
17 November 2020
Correct, Andrei! Thanks!
Andrei Level 41
26 October 2020
Does anyone know the difference between declaring an ArrayList like this:

ArrayList<String> list = new ArrayList<>();
and declaring an ArrayList like in the example shown above?

ArrayList<String> list = new ArrayList<String>();
Andrei Level 41
27 October 2020
I found the answer a few lessons after this, from Seb ! "Hi Henrique, the two declarations have the same effect. The first line is the old way of declaring it:

ArrayList<String> list = new ArrayList<String>();
And the following line is the shorter new way:

ArrayList<String> list = new ArrayList<>();
The second option is recommended. ;-) Cheers Seb"
Andrei Level 41
23 October 2020
Or, another easier way (in my opinion), to print the ArrayList in decreasing order is:

for (int i = list.size()-1; i >= 0; i--){
            System.out.println(list.get(i));
        }
instead of:

for (int i = 0; i < list.size(); i++)
{
  int j = list.size() - i - 1;
  System.out.println( list.get(j) );
}
Andrei Level 41
23 October 2020
I wrote list.size() - 1 because as we know, the computer starts counting from 0, so if you have 5 elements, the index of the last number will be 4. If you don't use -1 it will throw an error of being out of bounds. Hope it helps!
Karas Level 20, Tampa, United States
4 September 2020
I used it for some exercises before and the only thing I have to say is that seems it can not be used in for loop on cases where the ArrayList has no items in it, it has the size(), but can not be used unless there are already items inside. You can see that case in line 8 of the examples above.
Pavlo Plynko Level 41, Orlando, USA
4 June 2020
Add an element at the end of the array Array: This action is not supported ArrayList: list.add(s); So in an array if you have a null at the end you can't add anything? Perhaps it is worthwhile, by analogy with the delete operation, to indicate options for other operations. Or, for the delete operation, also write "This action is not supported" so as not to mislead people.