Share on Google+Share on Google+

Java arraylist generics example and arraylist generic list

Advertisement
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]

Advertisements

Advertisement

Posted on: October 23, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.