Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - ArrayList

java_List

ArrayList

ArrayList is same as Arrays with some added advantage. i.e. It can hold multiple data types(Integer, String etc.) & is growable.

In other words, you don't have to specify the size while declaring an ArrayList. As you go on adding the elments, it will grow automatically.



What is the default size of an ArrayList?

When the ArrayList is defined it is assigned with a default size of 10.


How to create an ArrayList?

ArrayList arrayList = new ArrayList();

The ArrayList will be created with the Initial capacity of 10. But offcourse it will grow as the elements are added.



How to create an ArrayList of a custom size?

Now, just think if someone wants to change the initial capacity( i.e 10). i.e. Say someone wants to create an ArrayList of size 50. ArrayList gives us the flexibility to do that as well.


ArrayList arrayList = new ArrayList(50);

Constructors in ArrayList

So, far we have seen three contructors :

  1. ArrayList() : Builds an ArrayList with initial capacity 10.

  2. ArrayList(int initialCapacity) : Builds an ArrayList with a custom initial capacity.

  3. ArrayList(Collection c) : Builds an ArrayList with any Collection as parameter.

We have seen as opposed to arrays ArrayList can hold multiple datatypes. i.e we can insert an Integer or String or Float in the same ArrayList.

But this advantage can be a big disadvantage at times.


Using Generics in ArrayList

And thus Generics was introduced. It ensures type safety.

i.e. Just like Arrays it will be holding a single datatype at a time.


ArrayList <String> arrayList = new ArrayList <String>();

The above created ArrayList will only be holding Strings. And if we try to insert anything other than Strings it would end up with an error.


Sorting, searching, deleting using ArrayList

So, first of all we will add three String objects in the ArrayList then sort it accordingly.


public class TestCollection{
  public static void main(String[] arg){

    String s1 = new String("Sham");
    String s2 = new String("Paul");
    String s3 = new String("John");

    // We will be adding these Strings to the ArrayList.
    ArrayList aListString = new ArrayList(); // Declare an ArrayList.
    aListString.add(s1); // Add the String to the List.
    aListString.add(s2);
    aListString.add(s3);

    System.out.println(aListString); // Output would be : [Sham,Paul,John]

    Collections.sort(aListString); // Sorts the ArrayList containing Strings.

    System.out.println(aListString); // New output would be : [John,Paul,Sham]

    String temp = aListString.get(2);
    System.out.println(temp); // Output will be : Sham

    aListString.remove(1); // Deletes 2nd element from the ArrayList.

    System.out.println(aListString); // New output would be : [John,Sham]

    if(aListString.contains("Sham")){

      System.out.println("Sham is present in the ArrayList.");
    }
  }
}

Above we have seen the following:

1) Creating an ArrayList:


ArrayList aListString = new ArrayList();

2) Adding the elements to the ArrayList using the add() method. Where s1,s2 and s3 are the String objects holding names.


aListString.add(s1);
aListString.add(s2);
aListString.add(s3);

Now the ArrayList contains the names in the following order:


java_ArrayList

As it happens in arrays, names are put into contigous memory locations.

3) Printing the contents of the ArrayList.


[John,Paul,Sham]

So, when we try to print the contents of the ArrayList using System.out.println(aListString);Its designed to print the '[' followed by the contents (i.e John, Paul, Sham) and ending with ']'. Its actually the toString() method which is overridden in the ArrayList to print in such way.

4) Sorting the List.


Collections.sort(aListString);

Here we are taking the help of the 'Collections' class(different from Collection Interface) to sort the ArrayList. Its pretty simple. Just take the help of the sort() method of Collections class and put the ArrayList object in it. And the rest will be taken care by Collections class.

So, the new content after sorting would be :


java_ArrayList

5) Finding an element from a particular location of ArrayList.


String temp = aListString.get(2);

So, we are going to get the element stored in the 2nd index of the ArrayList(i.e. Sham). For doing it ArrrayList provides us with a get() method. So, when we are putting the index value inside it, it returns the String in that particular location.

Thus we are using 'aListString.get(2)' the get() method and passing the 2 index in it. Since it is holding a String object, we have used the 'String temp' to store the fetched result.

6) Deleting an element from the ArrayList.


aListString.remove(1);

Similarly, ArrayList has a remove() method which is used to delete an element. You only have to tell the index(i.e 1 in this case).

So, we have 3 elements in the ArrayList. i.e.


java_ArrayList

Now, in the above statement we are trying to remove the element in the 1st index. So, 'Paul' will removed.

And the new output would be:


java_ArrayList

Advantages and Disadvantages of ArrayList :

Just consider a group of 500 students sitting in a hall based on their Roll Numbers. Off course they needs to sit on that particular seat which has their Roll Numbers pasted in it. Now, just imagine you are the mentor. Your task is to manage the students. So, lets relate this to ArrayList and see for what operations ArrayList is benefitial.



1) add() : Say a new student has come. So, all you need to do is assign him roll no 501 and show him his seat(Since there are 500 students). You can do it in a very short time. And so will ArrayList. So, ArrayList is good for addition of elements.

2) get() : You are given the Roll No of a student and asked to find him. Simply you will go to that particular seat(since the roll no is pasted on the seat). And find him. Very easy. So it will be easy for ArrayList as well. So its very good to find an element if the index is provided.

3) remove() : Now, consider a student is leaving(say roll no 2) permanently. So, you cannot leave that seat no 2 vacant. All you need to do is shift all the student one by one. i.e. Roll no 3 should be made roll no 2 and moved to seat no 2. Similarly roll no 4 should be made roll no 3 and moved to seat no 3. And this step should be repeated for all the 500 students. Just think the trouble you will face. The same trouble would be faced by ArrayList as well.Moral of the story. ArrayList is not good for deletion.

4) contains() : You are given the name of a student and check if he is present or not. Now, you cannot shout the name. All you can do is ask the names of each and every student starting from Roll No 1 until you find the actual one. Again trouble for you. So will be for ArrayList.

For sorting we have used the Collections class. i.e Collections.sort(aListString). Now Collections is a seperate class, and all we are doing is asking its sort() behaviour to sort the ArrayList for us, by passing the ArrayList object(i.e. aListString).

But in this case the sort() method is sorting a String object. So, its quite simple for sort(), as it knows it needs to sort a String based on the letters. But what about the Human object? Or any other object created by us.

We have Comparable and the Comparator for rescue which we will be seeing next.