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

 
 

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

Advertisement

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


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.

Posted on: October 23, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com