考虑以下 Employee 类和一个名为 Manager 的子类-
public class Employee
{
private String name;
public Employee(String name)
{
this.name = name;
}
public String getInfo()
{
return name;
}
}
public class Manager extends Employee
{
public Manager(String name)
{
super(name);
}
}
在另一个类中,我定义了两个函数如下 -
import java.util.ArrayList;
public class WildCardsAndTypeVariables
{
public static <T extends Employee> void displayInfo(ArrayList<T> employees)
{
for (int i=0; i<employees.size(); i++)
{
Employee employee = (Employee) employees.get(i);
System.out.println(employee.getInfo());
}
}
public static void displayInfo2(ArrayList<? extends Employee> employees)
{
for (int i=0; i<employees.size(); i++)
{
Employee employee = (Employee) employees.get(i);
System.out.println(employee.getInfo());
}
}
public static void main(String[] args)
{
Employee e1 = new Employee("John");
Employee e2 = new Employee("Joe");
Employee e3 = new Manager("Joseph");
ArrayList<Employee> employees = new ArrayList<Employee>();
employees.add(e1);
employees.add(e2);
employees.add(e3);
displayInfo(employees);
displayInfo2(employees);
}
}
我从 displayInfo() 和 displayInfo2() 得到相同的输出。
那么,考虑到这个例子,通配符和类型变量有什么区别呢?