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

ArrayList class in Java

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

How is Java Arraylist different from regular arrays?

In general, arrays are quite convenient and, as you have already noticed, you can do a lot of things with them :) However, arrays also have a number of disadvantages.
  • Limited size. You need to know already at the stage of creating an array how many cells it should contain. If you underestimate the required amount, there will not be enough space. If you overestimate it, the array will remain half empty, and that’s not so bad. After all, it turns out that you will also allocate more memory for it than necessary.
  • An array has no 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 “zeroed”.
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>();
Now we have created a list to store objects Cat. Pay attention:we do not specify the size of the ArrayList because it is automatically expandable. How is this possible? Easily. You will be surprised, but ArrayList is based on an ordinary array :) Yes, inside it there is an array in which our elements are stored. But ArrayList has a special mechanism for working with it:
  • When this internal array is full, the ArrayList creates a new array within itself. Its size = (size of old array * 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, an ArrayList (as opposed to an array) implements a method for adding a new element. This is a 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 also vice versa - it can find the index of an object in the ArrayList by reference to the object! To do this, it implements the method indexOf(): We pass into it a link to the desired object, and indexOf()it 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 actually 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 point to an index, that is, to a specific address in memory, such an array search 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='Бегемот'}
Moreover, you can easily find out whether an ArrayList contains a 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 whether the element is contained in the ArrayList's internal array, and returns the result in the form boolean- trueor false. Conclusion:

false
And another important thing about insertion. ArrayList 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)
To 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 the elements starting from [index]to the end of the array, and adds the object you need to the resulting empty cell. Here's 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 then 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 a method for this, Arrays.asList(). With its help, 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));
}
Please note: 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, it is generally possible to indicate it. ArrayList has a corresponding constructor. But its behavior in terms of adding new elements will not change:
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 easily 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 lecture, 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