泛型的重要性——举例说明
import java.util.*;
/**
*
* 泛型的好处是:在编译的时候检查类型安全,并且所有的强制转换都是自动和隐式的,提高代码的重用率
*
*/
public class test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/* 普通的写法
ArrayList al = new ArrayList();
//创建一只狗
Dog dog1 = new Dog();
//放入集合
al.add(dog1);
Dog temp = (Dog)(al.get(0));//强制转换
//Cat temp1 = (Cat)(al.get(0));//运行会出错
*/
//泛型的方法
ArrayList<Dog> al = new ArrayList<Dog>();
Dog dog1 = new Dog();
al.add(dog1);
Dog temp = al.get(0);//不需要强制转换了,自动转换
}
}
class Cat
{
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private int age;
}
class Dog
{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private int age;
}