5/26/2008

Java generics examples -- use generics in collection

Here are some most simple and common use of generics with collection.

Example 1:

List<String> names = new ArrayList<String>();
names.add("John");
System.out.printf("List<String> names: %s%n", names);
In the above example, names is a List of String. When retrieving elements from the List, the return value is of type String. So no need for casting, which is a big advantage over the old, non-parameterized collection.

Example 2:
Map<Integer, String> idToName = new HashMap<Integer, String>();
idToName.put(0, "John");
System.out.printf("Map<Integer, String> idToName: %s%n", idToName);
In the above example, idToName is a Map with a Integer key and String value. The output is:
Map<Integer, String> idToName: {0=John}

Example 3:
List<List<String>> listOfList = new ArrayList<List<String>>();
List<String> sublist1 = new ArrayList<String>();
sublist1.add("A String inside sublist1");
listOfList.add(sublist1);

List<String> sublist2 = new LinkedList<String>();
sublist2.add("A String inside sublist2");
listOfList.add(sublist2);
System.out.printf("List<List<String>> listOfList: %s%n", listOfList);
The above example shows a List whose elements are of type List, i.e., a List of List. The inner List declares that it can only hold String elements. The first inner list is an ArrayList of String, and the second is a LinkedList of String. Running this code snippet prints:
List<List<String>> listOfList: [[A String inside sublist1], [A String inside sublist2]]

Example 4:
private static <T> List<T> extractElements(List bag, Class<T> type) {
List<T> result = new ArrayList<T>();
for(Object e : bag) {
//if(e instanceof T) can't use instanceof
if(type.isAssignableFrom(e.getClass())) {
result.add((T) e);
}
}
return result;
}
This method takes a List of mixed elements and extracts those elements of the desired type. The following shows how to call this method:
List bag = new ArrayList();
bag.add(new Integer(0));
bag.add(new Integer(1));
bag.add(new Double(2008.5));
bag.add("a string");
List<Number> numbersInBag = extractElements(bag, Number.class);
System.out.printf("All elements in bag: %s%nNumber elements in bag: %s%n",
bag, numbersInBag);
List<Integer> integersInBag = extractElements(bag, Integer.class);
System.out.printf("All elements in bag: %s%nInteger elements in bag: %s%n",
bag, integersInBag);
-------- output -----------

All elements in bag: [0, 1, 2008.5, a string]
Number elements in bag: [0, 1, 2008.5]
All elements in bag: [0, 1, 2008.5, a string]
Integer elements in bag: [0, 1]

10 comments:

Kris said...

Thanks for the post. I have one question:

What is the reason for declaring your collections as superclass objects? That is, "List" instead of "ArrayList"?

Example:
List<String> names = new ArrayList<String>()

I remember seeing a note about this from PMD or Checkstyle, but don't remember the reason.

Thanks

javahowto said...

We can easily change to use another impl of List, say, LinkedList, instead of ArrayList. We only need to change how this variable (names) is initialized, without touching the rest of the app.

All the methods we need are in List interface, and don't need any ArrayList-specific methods. It's sufficient to know it as a List.

tipcorner said...

can you explain example like List
Thanks

infochannel said...

can you explain example like List
Thanks

Anonymous said...

List example

what is class in java said...

great example, I always like learning by example. You can also see this article for more examples How Generics works in Java

Explain Java 5 features said...

Very useful information on Generics. Thank you.

Anonymous said...

Why is this called generic when it is specific to certain type or object

Steve Smith said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions








Java Course in Chennai

Java Online Training India

Anonymous said...

Great Example !!

There are some Java books that cover this topic pretty well !!