歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中泛型之類型通配符(?)

Java中泛型之類型通配符(?)

日期:2017/3/1 10:08:26   编辑:Linux編程

實體類

package cn.xy.model;

/**
* 生物類
* @author xy
*
*/
public class Living
{
private String name;

public Living(String name)
{
super();
this.name = name;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

@Override
public String toString()
{
return name;
}
}

/**
* 動物類
* @author xy
*
*/
public class Animal extends Living
{
public Animal(String name)
{
super(name);
}
}

/**
* 貓類
* @author xy
*
*/
public class Cat extends Animal
{
public Cat(String name)
{
super(name);
}
}


/**
* 狗類
* @author xy
*
*/
public class Dog extends Animal
{
public Dog(String name)
{
super(name);
}
}

測試類1

import java.util.ArrayList;
import java.util.List;
import cn.xy.model.Animal;
import cn.xy.model.Cat;
import cn.xy.model.Dog;
import cn.xy.model.Living;

public class Test
{


/**
* 雖Cat和Dog是Animal的子類,但List<Cat>和List<Dog>不是List<Animal>的子類,直接為該方法傳入List<Cat>和List<Dog>編譯

* 會錯誤。如List<Stirng>不是List<Object>的子類一樣。
*/
public static void GetNames1(List<Animal> animals)
{
for (Animal a : animals)
{
System.out.println(a.getName());
}
}

/**
* 該方法使用類型通配符,可以使用任何類型的List來調用它,其類型均為Object
*/
public static void GetNames2(List<?> animals)
{
for (Object obj : animals)
{
Animal a = (Animal) obj;
System.out.println(a.getName());
}
}

/**
* 該方法設置了類型通配符的上限,即傳入的List的類型必須是Animal的子類或者Animal本身
*/
public static void GetNames3(List<? extends Animal> animals)
{
for (Animal a : animals)
{
System.out.println(a.getName());
}
}

/**
* 該方法設置了類型通配符的下限,即傳入的List的類型必須是Animal的父類或者Animal本身
*/
public static void GetNames4(List<? super Animal> animals)
{
for (Object a : animals)
{
System.out.println(a);
}
}

public static void main(String[] args)
{
List<Cat> cats = new ArrayList<Cat>();
cats.add(new Cat("Tomcat"));
cats.add(new Cat("Tomcat2"));

List<Dog> dogs = new ArrayList<Dog>();
dogs.add(new Dog("Tomdog"));
dogs.add(new Dog("Tomdog2"));

List<Living> livings = new ArrayList<Living>();
livings.add(new Living("living1"));
livings.add(new Living("living2"));

// GetNames1(cats);
// GetNames1(dogs);
GetNames2(cats);
GetNames2(dogs);
GetNames3(cats);
GetNames3(dogs);
// GetNames4(cats);
// GetNames4(dogs);
GetNames4(livings);

}
}


測試類2

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

public class Test2
{

/**
* 添加的對象必須是和?一樣的類型或者是其子類,但並不知道?是什麼類型。所以lst.add會產生編譯錯誤,故不能向其中添加對象
* null值是一個例外,因為null是所有引用類型的實例
*/
public static void main(String[] args)
{
List<?> lst = new ArrayList<String>();
// lst.add("str");
}

}

Copyright © Linux教程網 All Rights Reserved