您的位置:首页 > 编程语言 > Java开发

Java泛型实例

2010-09-15 21:58 302 查看
Java泛型实例:

 

/**
*
*/
package com;

/**
* @author Administrator
*
*/
public class AnimalDoctor {

/**
* @param args
*/
public static void main(String[] args) {
// test it
Dog[] dogs = {new Dog(), new Dog()};
Cat[] cats = {new Cat(), new Cat(), new Cat()};
Bird[] birds = {new Bird()};
AnimalDoctor doc = new AnimalDoctor();
doc.checkAnimals(dogs); // pass the Dog[]
doc.checkAnimals(cats); // pass the Cat[]
doc.checkAnimals(birds); // pass the Bird[]
}

public void checkAnimal(Animal a) {
a.checkup(); // does not matter which animal subtype each
// Animal's overridden checkup() method runs
}

public void checkAnimals(Animal[] animals) {
for (Animal a : animals) {
a.checkup();
}
}
}

abstract class Animal {
public abstract void checkup();
}

class Dog extends Animal {
public void checkup() { // implement Dog-specific code
System.out.println("Dog checkup");
}
}

class Cat extends Animal {
public void checkup() { // implement Cat-specific code
System.out.println("Cat checkup");
}
}

class Bird extends Animal {
public void checkup() { // implement Bird-specific code
System.out.println("Bird checkup");
}
}


 

Dog checkup
Dog checkup
Cat checkup
Cat checkup
Cat checkup
Bird checkup

 

 

/**
*
*/
package com;

import java.util.ArrayList;
import java.util.List;

/**
* @author Administrator
*
*/
public class AnimalDoctorGeneric {
// change the argument from Animal[] to ArrayList<Animal>
public void checkAnimals(List<? extends Animal> animal) {
for (Animal a : animal) {
a.checkup();
}
}

public static void main(String[] args) {
// make ArrayLists instead of arrays for Dog, Cat, Bird
List<Dog> dogs = new ArrayList<Dog>();
dogs.add(new Dog());
dogs.add(new Dog());
ArrayList<Cat> cats = new ArrayList<Cat>();
cats.add(new Cat());
cats.add(new Cat());
List<Bird> birds = new ArrayList<Bird>();
birds.add(new Bird());
// this code is the same as the Array version
AnimalDoctorGeneric doc = new AnimalDoctorGeneric();
// this worked when we used arrays instead of ArrayLists
doc.checkAnimals(dogs); // send a List<Dog>
doc.checkAnimals(cats); // send a List<Cat>
doc.checkAnimals(birds); // send a List<Bird>
}
}


 

Dog checkup
Dog checkup
Cat checkup
Cat checkup
Bird checkup

 

 

List<? extends Animal> aList = new ArrayList<Dog>();

在上文件中可以使用

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java arrays class string