google search

Custom Search

Friday, August 8, 2008

Summary of Generics and Questions and Exercises: Generics

This chapter described the following problem: We have a Box class, written to be generally useful so it deals with Objects. We need an instance that takes only Integers. The comments say that only Integers go in, so the programmer knows this (or should know it), but the compiler doesn't know it. This means that the compiler can't catch someone erroneously adding a String. When we read the value and cast it to an Integer we'll get an exception, but that's not ideal since the exception may be far removed from the bug in both space and time:

1. Debugging may be difficult, as the point in the code where the exception is thrown may be far removed from the point in the code where the error is located.

2. It's always better to catch bugs when compiling than when running.

Specifically, you learned that generic type declarations can include one or more type parameters; you supply one type argument for each type parameter when you use the generic type. You also learned that type parameters can be used to define generic methods and constructors. Bounded type parameters limit the kinds of types that can be passed into a type parameter; they can specify an upper bound only. Wildcards represent unknown types, and they can specify an upper or lower bound. During compilation, type erasure removes all generic information from a generic class or interface, leaving behind only its raw type. It is possible for generic code and legacy code to interact, but in many cases the compiler will emit a warning telling you to recompile with special flags for more details.

For additional information on this topic, see Generics by Gilad Bracha.

Questions

1. Consider the following classes:

public class AnimalHouse {
private E animal;
public void setAnimal(E x) {
animal = x;
}
public E getAnimal() {
return animal;
}
}

public class Animal{
}

public class Cat extends Animal {
}

public class Dog extends Animal {
}

For the following code snippets, identify whether the code:

* fails to compile,
* compiles with a warning,
* generates an error at runtime, or
* none of the above (compiles and runs without problem.)

a. AnimalHouse house = new AnimalHouse();

b. AnimalHouse house = new AnimalHouse();

c. AnimalHouse house = new AnimalHouse();
house.setAnimal(new Cat());

d. AnimalHouse house = new AnimalHouse();
house.setAnimal(new Dog());

Exercises

1. Design a class that acts as a library for the following kinds of media: book, video, and newspaper. Provide one version of the class that uses generics and one that does not. Feel free to use any additional APIs for storing and retrieving the media.

0 comments:

 

blogger templates | Make Money Online