Java arraylist generics example and arraylist generic list


 

Java arraylist generics example and arraylist generic list

This Java Tutorial section demonstrates the use of the generic ArrayList in Java Program.

This Java Tutorial section demonstrates the use of the generic ArrayList in Java Program.

  • Generics is used to make  the data type safe program. It is the new feature of java 5.
  • When the ArrayList is generalized for a specific data type, other data types cannot be added.
  • It gives error on using the other data type element.


Example of Java Generic Arraylist
import java.util.ArrayList;
import java.util.List;

public class GenericList1 {
    public static void main(String[] args) {
      List list=new ArrayList();
         list.add("aaa");
         list.add("bbb");
         list.add(1000);
         list.add("ccc");
         list.add("ddd");
         System.out.println(list);
    }
}
It gives compilation error
GenericList1.java:9: cannot find symbol
symbol : method add(int)
location: interface java.util.List
list.add(1000);
^
1 error
Example-2
import java.util.ArrayList;
import java.util.List;

public class GenericList2 {
    public static void main(String[] args) {
      List list=new ArrayList();
         list.add("aaa");
         list.add("bbb");
         list.add("fff");
         list.add("ccc");
         list.add("ddd");
         System.out.println(list);
    }
}
Output
[aaa, bbb, fff, ccc, ddd]

Ads