站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

Questions and Exercises: Generics - Java Tutorial 5.0 英文版

The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Classes and Inheritance

Questions and Exercises: Generics

Questions

1. Consider the following classes:
public class AnimalHouse<E> {
    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:
  1. fails to compile
  2. compiles with a warning
  3. generates an error at runtime
  4. none of the above (compiles and runs without problem)
a. AnimalHouse<Animal> house = new AnimalHouse<Cat>();

b. AnimalHouse<Dog> house = new AnimalHouse<Animal>();

c. AnimalHouse<?> house = new AnimalHouse<Cat>();
   house.setAnimal(new Cat());

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

Exercises

1. Write an example that sorts a set of predefined strings based on string length. Use the version of the Collections.sort method that takes a Comparator parameter.

Check your answers. (in the Learning the Java Language trail)


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.