1 动因:比如在集合类中,JDK 1.5前,加入元素是object的,取出来的话要转型时,有可能会在运行期出错,所以
用范型的话,可以在编译期间发现了.
2 举例:
public static void main(String args[]){
Vector<String> v = new Vector<String>();
v.addElement("Tom");
v.addElement("Billy");
v.addElement("Nancy");
v.addElement(new Date());
v.addElement(new Integer(300));
for(int i=0;i<v.size();i++){
String name = v.elementAt(i);
System.out.println(name);
}
不用转型了.
3 范型的hashtable的话,也可以存对象,比如有一个pojo employee.java,则
Hashtable<Integer,Employee> ht = new Hashtable<Integer,Employee>();
ht.put(101,new Employee(101,"张三",5000));
ht.put(102,new Employee(102,"李四",4800));
ht.put(106,new Employee(106,"赵六",8620));
4 类中带范型的例子,比如一个类
public class Person<T>{
private final int id;
private T secrecy;
public Person(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setSsecrecy(T secrecy){
this.secrecy = secrecy;
}
public T getSecrecy(){
return secrecy;
}
}
实际使用的时
Person<String> p1 = new Person<String>(101);
p1.setSsecrecy("芝麻开门");
String s = p1.getSecrecy();
System.out.println(p1.getId() + "\t密码是:" + s);
5 import java.util.Vector;
public class Test{
public static void main(String[] args){
Test t = new Test();
String valid = t.evaluate("tiger","tiger");
Integer i = t.evaluate(new Integer(300),new Integer(350));
System.out.println(valid);
System.out.println(i);
}
public <T> T evaluate(T a,T b){
if(a.equals(b))
return a;
else
return null;
}
}
6 范型的上限例子,如
import java.lang.Number;
public class Point<T extends Number>{
private T x;
private T y;
public Point(){
}
public Point(T x, T y){
this.x = x;
this.y = y;
}
public T getX(){
return x;
}
public T getY(){
return y;
}
public void setX(T x){
this.x = x;
}
public void setY(T y){
this.y = y;
}
public void showInfo(){
System.out.println("x=" + x + ",y=" + y);
}
}
这里规定了T只能是数值类型的了,使用时
Point<Integer> pi = new Point<Integer>(20,40);
pi.setX(pi.getX() + 100);
pi.showInfo();
Point<Double> pd = new Point<Double>();
pd.setX(3.45);
pd.setY(6.78);
pd.showInfo();
要注意的是,比如List<?> foo=new ArrayList<? extends animal>只错误的,对象的创建中不语序用通配符号