View RSS Feed

Advanced Java

Java Generic's Wildcards

Rate this Entry
by , 02-18-2012 at 03:57 PM (754 Views)
Consider a situation where you desire all List elements to be printed. This could be explained by the given code:
Java Code: This is the code to explain printing of all elements
public void processElements(List<Object> elements){
   for(Object o : elements){
      System.out.println(o);
   }
}
This method couldn’t be used along with List<String> instance. To sort out this problem, wildcard operator is used. For writing generic List by the help of wildcard operator, use this code.
Java Code: This is the code to explain wildcard operator
List<?> listOfUnknown = new ArrayList<?>();    
//ProcessElements() method could be defined as following: 
public void processElements(List<?> elements){
   for(Object o : elements){
      System.out.println(o);
   }
}
//ProcessElements() could be called with any kind of generified List instance. For Example: 
List<String> elements = new ArrayList<String>
// ... add String elements to the list.
processElements(elements);

Submit "Java Generic's Wildcards" to Facebook Submit "Java Generic's Wildcards" to Digg Submit "Java Generic's Wildcards" to del.icio.us Submit "Java Generic's Wildcards" to StumbleUpon Submit "Java Generic's Wildcards" to Google

Categories
Generics

Comments