Friday, October 30, 2009

Section 13.5. The Get and Put Principle







13.5. The Get and Put Principle

As also specified in Java Generics and Collections, the Get and Put Principle details the best usage of extends and super wildcards:

  • Use an extends wildcard when you get only values out of a structure.

  • Use a super wildcard when you put only values into a structure.

  • Do not use a wildcard when you both get and put values into a structure.

The extends wildcard has been used in the method declaration of the addAll( ) method of the List collection, as this method gets values from a collection.

	public interface List <E> extends Collection<E>{
boolean addALL(Collection <? extends E> c)
}

List<Integer> srcList = new ArrayList<Integer>( );
srcList.add(0);
srcList.add(1);
srcList.add(2);
// Using addAll( ) method with extends wildcard
List<Integer> destList = new ArrayList<Integer>( );
destList.addAll(srcList);


The super wildcard has been used in the method declaration of the addAll() method of the class Collections, as the method puts values into a collection.

	public class Collections {
public static <T> boolean addAll
(Collection<? super T> c, T... elements){...}
}

// Using addAll( ) method with super wildcard
List<Number> sList = new ArrayList<Number>( );
sList.add(0);
Collections.addAll(sList, (byte)1, (short)2);









No comments:

Post a Comment