泛型类:
-
1.定义泛型类
Point <T> == 类名<T> 在类名的后面加一个尖括号,括号里面是一个大写字母,推荐各位同学使用T大写字母
-
2.类中使用泛型
T表示派生自Object类的任何类型,比如 Integer Float 还可以用String 尖括号中你传入的是什么,T就代表什么类型,这就是泛型类的最大作用
-
3.使用泛型类比我们使用Object类的好处如下:
(1)不用类型强制转换 (2)在设置值的时候(调用set访问器的时候),换入类型不符合会报错
下面是一个实例
Student类:
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int age, String name) {
super();
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Student [age=" + age + ", name=" + name + "]";
}
}
Point泛型类
import java.util.AbstractList;
import java.util.List;
import java.util.RandomAccess;
public class Point<T> {
private T x;
private T y;
public T getX() {
return x;
}
public void setX(T x) {
this.x = x;
}
public T getY() {
return y;
}
public void setY(T y) {
this.y = y;
}
}
测试泛型类的使用
import java.util.ArrayList;
import java.util.List;
public class TestPoint {
public static void main(String[] args) {
// 构建泛型类的对象 Integer型
Point<Integer> p = new Point<Integer>();
p.setX(new Integer(88));
Integer x = p.getX();
System.out.println(x);
// 构建泛型类的对象 Float型
Point<Float> p1 = new Point<Float>();
p1.setX(new Float(80));
Float x1 = p1.getX();
System.out.println(x1);
// 构建泛型类的对象 Student型
Point<Student> p3 = new Point<Student>();
p3.setX(new Student(40,"xiaoxiao"));
System.out.println(p3.getX());
}
}