Home > Articles > Programming > Java

  • Print
  • + Share This

Beyond the simple and useful example of generics and the Java collections classes, there are aspects of generics in Java that are a little more difficult to become accustomed to. These aspects include the concept and usage of raw types, wildcards, exceptions, and new rules governing inheritance and method overloading.

Raw Types

To maintain backward compatibility, a parameterized type can be used without specifying type parameters. This type is called a raw type.

For example, the following code is perfectly legal, even if List and ArrayList are parameterized types:

 List myList = new ArrayList();

In addition, assignments can be made from a raw type to its parameterized version and back. For example, a List<String> may be assigned to a List, and a List may be assigned to a List<String>. The second assignment, from parameterized type to raw type, will generate a compiler warning because the raw List can contain elements that are not Strings.

Method calls to raw types will also generate compiler warnings if the method's signature was changed during the type erasure process.

The notion of raw types is supported for backward compatibility; however, code that mixes the use of parameterized types and their raw versions loses a great deal of the type safety promised by generics. For example, consider the code in Listing 7.

Listing 7 Raw types example

1 // myList is raw
2 List myList;
3    
4 // stringList is a list of String
5 List<String> stringList = new ArrayList<String>();
6 // stringList.add(new Integer(123)); // would not compile
7    
8 // assign the List<String> to the raw List
9 myList = stringList;
10    
11 // we can add whatever we want
12 myList.add(new Integer(123)); // compiler warning

In the preceding example, we create an ArrayList<String> (which should contain only Strings as elements), and assign it to myList, which is of type raw List. Next, we use myList to add an element of type Integer to the collection. This call generates a compiler warning, but it is successful, demonstrating a potential danger in using raw types.

Wildcards

When no specific knowledge of the value of a type parameter is needed, it can be replaced by a wildcard. The wildcard alone, represented by a question mark, takes the value of the default bound of the corresponding formal type parameter, which is Object in following example:

 void printElements(List<?> myList) { ... }

A wildcard might include an upper bound, which states that the value of the type parameter must be equal to, or a descendent of the bound, as in the following:

 void addAll(Collection<? extends E>) { ... {

A wildcard may alternately specify a lower bound, as in the following:

 void addAll(Collection<? super E>) { ... {

To better understand wildcards at work, consider the example shown in Listing 8).

Listing 8 List convergence using wildcards.

1  void testList() {
2    List<Number> numberList = new ArrayList<Number>();
3    numberList.add(new Integer(123));
4    numberList.add(new Double(3.14));
5    
6    List<Integer> integerList = new ArrayList<Integer>();
7    integerList.add(new Integer(123));
8    
9    // add1(numberList, integerList); // compile-time error
10    add2(numberList, integerList); 
11    add3(numberList, integerList);
12  }
13  
14  <T> void add1(List<T> to, List<T> from) {
15    for (Iterator<T> i = from.iterator(); i.hasNext(); )
16      to.add(i.next());
17  }
18  
19  <T> void add2(List<T> to, List<? extends T> from) {
20    for (Iterator<? extends T> i = from.iterator(); i.hasNext(); )
21        to.add(i.next());
22  }
23  
24  <T> void add3(List<? super T> to, List<T> from) {
25    for (Iterator<T> i = from.iterator(); i.hasNext(); )
26      to.add(i.next());
27  }

In this example, the testList() method creates a List<Integer> and a List<Number> and then attempts to call all three add methods (add1, add2, and add3). Each add method attempts to add the elements of the List<Integer> to the List<Number>, which should be possible because Integer extends Number.

The first add method, add1(...), is declared to take two arguments, both declared as List<T>. Our call to add1(...) does not even compile because the type parameter T cannot be bound to both Number and Integer.

The second add method, add2(...), demonstrates the "? extends T" wildcard notation. In this case, the method is declared to take a "List of T" and a "List of things that extend T." Calling this method with a "List of Numbers" and a "List of Integers" works because Integer extends Number.

The last add method, add3(...), also works. It is declared to take as parameters a "List of super classes of T" and a "List of T."

Exception Handling

Type parameters may be used in the throws clause of a method declaration, but (to preserve JVM compatibility) not in a catch clause. Listing 9 shows an example.

Listing 9 Generic exception handling.

1 public interface MyAction <E extends Exception> {
2  public void doWork() throws E;
3 }
4  
5 public class MyFileAction implements MyAction<FileNotFoundException> {
6  public void doWork() throws FileNotFoundException {
7   new File("/foo/bar.txt");
8   // do something here...
9  }
10 }
11    
12 // client code
13 MyFileAction fileAction = new MyFileAction();
14  try {
15   fileAction.doWork();
16  } 
17  catch (FileNotFoundException e) {
18   e.printStackTrace();
19  }  

Inheritance and Overloading

Classes can extend generic classes, and provide values for type parameters or add new type parameters by in doing so. For example, all the following are legal:

 class MyStringList extends ArrayList<String> { ... }
 class A<X, Y, Z> { ... }
 class B<M,N> extends A<N, String, Integer> { ... }

The addition of generics does, however, change the rules of method overriding slightly. Note in the first example above (MyStringList) the effective signatures of the 'get' method in ArrayList and our subclass:

ArrayList:
 public Object get(int i);
MyStringList:
 public String get(int i);

Through inheritance, the return type has changed. Prior to Java 1.5, this would not have been legal; however, with the addition of parameterized types, the rule has change from "the return types must be identical" to "the return type of the method must be a subtype of all the methods it overrides." As such, the following, which would not compile in a 1.4 environment, is perfectly acceptable in 1.5:

  public class Parent {
    public Number getX() { ... }
  }
  public class Child extends Parent {
    public Integer getX() { ... }
  }
  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.