Home Tutorial Java Collections Arraylist Java arraylist generics example and arraylist generic list

 
 

Java arraylist generics example and arraylist generic list
Posted on: October 23, 2009 at 12:00 AM
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]

Related Tags for Java arraylist generics example and arraylist generic list:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.