JavaRush /Java Blog /Random EN /ArrayList class in Java

ArrayList class in Java

Published in the Random EN group
Hello! In previous lectures, we analyzed in detail such a data structure as an array and examined common examples of working with them. But this data structure has a number of drawbacks. The answer to them in Java was the appearance of ArrayList. To put it as simply as possible, the ArrayList list in Java is a “pumped” array with a lot of new features.ArrayList class - 1

How is Java Arraylist different from normal arrays?

In general, arrays are quite convenient and, as you have already noticed, you can do a lot of things with them :) Nevertheless, arrays have a number of disadvantages.
  • Limited size. You need to know at the stage of creating an array how many cells it should contain. Underestimate the right amount - there will not be enough space. Overestimate - the array will remain half empty, and this is not so bad. After all, it turns out that you will also allocate more memory for it than you need.
  • An array does not have methods for adding elements. You always have to explicitly specify the index of the cell where you want to add the element. If you accidentally specify an already occupied cell with some desired value, it will be overwritten.
  • There are no methods to remove an element. The value can only be reset.
public class Cat {

   private String name;

   public Cat(String name) {
       this.name = name;
   }

   public static void main(String[] args) {

       Cat[] cats = new Cat[3];
       cats[0] = new Cat("Thomas");
       cats[1] = new Cat("Hippopotamus");
       cats[2] = new Cat("Philip Markovich");

       cats[1] = null;



       System.out.println(Arrays.toString(cats));
   }

   @Override
   public String toString() {
       return "Cat{" +
               "name='" + name + '\'' +
               '}';
   }
}
Conclusion:

[Cat{name='Томас'}, null, Cat{name='Фorпп Маркович'}]
All these shortcomings can be eliminated using ArrayList. It is created very simply:
ArrayList<Cat> cats = new ArrayList<Cat>();
We have now created a list to hold objects Cat. Pay attention:we don't specify the size of the ArrayList because it is auto-expandable. How is this possible? Easily. You will be surprised, but ArrayList is based on the most ordinary array :) Yes, it has an array inside, in which our elements are stored. But ArrayList has a special mechanism for working with it:
  • When this internal array fills up, ArrayList creates a new array internally. Its size = (old array size * 1.5) +1.
  • All data is copied from the old array to the new one
  • The old array is removed by the garbage collector.
Thanks to this mechanism, ArrayList'e (unlike an array) has a method for adding a new element. This is the method add().
public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<Cat>();
   cats.add(new Cat("Hippopotamus"));
}
The new element is added to the end of the list. Now there is no risk of overflow, so this mechanism is completely safe. By the way, ArrayList can not only search for an object by index, but vice versa - it can find the index of an object in an ArrayList by reference to an object! To do this, it implements the method indexOf(): We pass a reference to the desired object into it, and indexOf()returns its index to us:
public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();
   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Hippopotamus");
   Cat philipp = new Cat("Philip Markovich");
   Cat pushok = new Cat("Fluff");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(philipp);
   cats.add(pushok);

   int thomasIndex = cats.indexOf(thomas);
   System.out.println(thomasIndex);
}
Conclusion:

0
That's right, the object thomasis indeed stored in the cell 0. Arrays have not only disadvantages, but also undoubted advantages. One of them is searching for an element by index. Since we are pointing to an index, that is, to a specific address in memory, such an array lookup is very fast. ArrayList in Java can do this too! To do this, it implements a method get():
public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();
   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Hippopotamus");
   Cat philipp = new Cat("Philip Markovich");
   Cat pushok = new Cat("Fluff");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(philipp);
   cats.add(pushok);

   Cat secondCat = cats.get(1);

   System.out.println(secondCat);
}
Conclusion:

Cat{name='Бегемот'}
In addition, one can easily find out if the ArrayList contains any particular object or not. This is done using the method contains():
public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();
   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Hippopotamus");
   Cat philipp = new Cat("Philip Markovich");
   Cat pushok = new Cat("Fluff");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(philipp);
   cats.add(pushok);

   cats.remove(pushok);
   System.out.println(cats.contains(pushok));
}
The method checks if the element is contained in the ArrayList's internal array, and returns the result in the form boolean- trueor false. Conclusion:

false
And one more important thing about insertion. ArrayList class - 2ArrayList allows you to insert data not only at the end of the array, but also into any cell by index. It has two methods for this:
  • add(int index, Cat element)
  • set(int index, Cat element)
In both, you pass the index of the cell into which you want to insert, and a link to the object itself. The difference is that pasting through set()overwrites the old value stored in the cell. And inserting through add()first shifts all elements starting from [index]to the end of the array, and adds the object you need to the resulting empty cell. Here is an example:
public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();
   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Hippopotamus");
   Cat philipp = new Cat("Philip Markovich");
   Cat pushok = new Cat("Fluff");

   cats.add(thomas);
   cats.add(behemoth);

   System.out.println(cats.toString());

   cats.set(0, philipp);//Now we have a list of 2 cats. We add the 3rd via set:

   System.out.println(cats.toString());
}
Conclusion:

[[Cat{name='Томас'}, Cat{name='Бегемот'}]
[Cat{name='Фorпп Маркович'}, Cat{name='Бегемот'}]
We had a list of 2 cats, we inserted another one through the method set()into the cell 0. As a result, the old value stored in this cell was replaced with a new one.
public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();
   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Hippopotamus");
   Cat philipp = new Cat("Philip Markovich");
   Cat pushok = new Cat("Fluff");

   cats.add(thomas);
   cats.add(behemoth);

   System.out.println(cats.toString());

   cats.add(0, philipp);//Now we have a list of 2 cats. Add the 3rd via add

   System.out.println(cats.toString());
}
But it add()worked differently. He shifted all the elements to the right and after that wrote the new value into the cell 0. Conclusion:

[Cat{name='Томас'}, Cat{name='Бегемот'}]
[Cat{name='Фorпп Маркович'}, Cat{name='Томас'}, Cat{name='Бегемот'}]
To completely clear the list, use the method clear():
public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();
   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Hippopotamus");
   Cat philipp = new Cat("Philip Markovich");
   Cat pushok = new Cat("Fluff");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(philipp);
   cats.add(pushok);

   cats.clear();

   System.out.println(cats.toString());
}
Conclusion:

[]
All content has been removed from the list. By the way, pay attention: unlike arrays, in ArrayList the toString() method is overridden and immediately displays the list in string format. In the case of arrays, we had to use the Arrays class for this. And since we remembered Arrays: in Java, you can easily “switch” between an array and an ArrayList, that is, convert one to the other. The Arrays class has the Arrays.asList() method for this. With it, we get the contents of the array as a list and pass it to the constructor of our ArrayList:
public static void main(String[] args) {

   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Hippopotamus");
   Cat philipp = new Cat("Philip Markovich");
   Cat pushok = new Cat("Fluff");

   Cat[] catsArray = {thomas, behemoth, philipp, pushok};

   ArrayList<Cat> catsList = new ArrayList<>(Arrays.asList(catsArray));
   System.out.println(catsList);
}
Conclusion:

[Cat{name='Томас'}, Cat{name='Бегемот'}, Cat{name='Фorпп Маркович'}, Cat{name='Пушок'}]
You can do the opposite - get an array from an ArrayList object. To do this, use the toArray() method:
public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();

   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Hippopotamus");
   Cat philipp = new Cat("Philip Markovich");
   Cat pushok = new Cat("Fluff");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(philipp);
   cats.add(pushok);

   Cat[] catsArray = cats.toArray(new Cat[0]);

   System.out.println(Arrays.toString(catsArray));
}
Note that we passed an empty array to the toArray() method. It's not a mistake. Inside the ArrayList class, this method is implemented in such a way that passing an empty array increases its performance. For now, just remember this for the future (but you can also transfer a specific size, it will work). Speaking of size. The current size of the list can be found using the method size():
public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>();


   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Hippopotamus");
   Cat philipp = new Cat("Philip Markovich");
   Cat pushok = new Cat("Fluff");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(philipp);
   cats.add(pushok);

   System.out.println(cats.size());
}
It is important to understand here that, unlike the lengtharray property, the ArrayList.size() method returns exactly the number of elements, and not the initial capacity, because we do not specify it when creating the ArrayList. By the way, you can specify it in general. ArrayList has a corresponding constructor. But its behavior in terms of adding new elements will not change from this:
public static void main(String[] args) {

   ArrayList<Cat> cats = new ArrayList<>(2);//create an ArrayList with an initial capacity of 2


   Cat thomas = new Cat("Thomas");
   Cat behemoth = new Cat("Hippopotamus");
   Cat philipp = new Cat("Philip Markovich");
   Cat pushok = new Cat("Fluff");

   cats.add(thomas);
   cats.add(behemoth);
   cats.add(philipp);
   cats.add(pushok);

   System.out.println(cats.size());
}
Console output:

4
We created a list with 2 elements, but when we needed it, it quietly expanded. Another thing is that if we initially created a very small list, it will have to carry out the expansion operation more often, and this consumes a certain amount of resources. In this lesson, we barely touched on the process of removing elements from an ArrayList. Of course, this is not due to forgetfulness. This topic has been separated into a separate lecture, which you can read further :)
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION