A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

ArrayList in Java

To create ArrayList object we have to import util package and then need to create object.
After created object of ArrayList, we can store any type of element in this list or group of objects, duplicate object/elements. If you do not want to store such way then need to define generic type that will be the next example. Let’s see the first program.

import java.util.ArrayList;

public class TestArrayListClass {

      public static void main(String[] args) {
           
            //create arrayList
            ArrayList aList = new ArrayList();
           
            //add elements in list
            aList.add(10);
            aList.add("programming");
            aList.add(123);
            aList.add("shifts");
           
            System.out.println(aList);   //[10, programming, 123, shifts]

      }

}



After defining the generic type, as list
//create arrayList
ArrayList<String> aList = new ArrayList<String>();
We can only store element as type like String, otherwise it will give compile time error.


import java.util.ArrayList;

public class TestArrayListClass {

       public static void main(String[] args) {
            
             //create arrayList
             ArrayList<String> aList = new ArrayList<String>();
             aList.add("programming");
             aList.add("shifts");
              System.out.println(aList);   //[programming,shifts]

       }

}

Otherwise, it will give compile time exception will look like as below.



If we define the generic type and gives different type in the list then an exception will be generated like in this example.
import java.util.ArrayList;

public class TestArrayListClass {

       public static void main(String[] args) {
            
             //create arrayList
             ArrayList<String> aList = new ArrayList<String>();
            
             //add elements in list
             aList.add(10);  //compile time exception
             aList.add("programming");
             aList.add(123);  //compile time exception
             aList.add("shifts");
            
              System.out.println(aList);  
       }

}

If we run then we will get as below:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
       The method add(int, String) in the type ArrayList<String> is not applicable for the arguments (int)
       The method add(int, String) in the type ArrayList<String> is not applicable for the arguments (int)

       at packagename.TestArrayListClass.main(TestArrayListClass.java:13)












LEARN TUTORIALS

.

.