现在的位置: 首页 > 综合 > 正文

java中泛型学习1之类型通配符(?)

2014年09月05日 ⁄ 综合 ⁄ 共 2294字 ⁄ 字号 评论关闭

 

实体类

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");
 }

}

 

 

抱歉!评论已关闭.