1. 认识泛型展开目录
- 泛型是在 JKD1.5 之后增加的新功能
- 泛型可以解决数据类型的安全性问题,它的主要原理,是在类声明的时候通过一个标识表示类中的某个属性的类型或者某个方法的返回值及参数类型
- 泛型不能用基本数据类型,要用其包装类
- 格式:
- 对象的创建
class A{
private Object m;
public void setM(Object m){
this.m = m;
}
public Object getM(){
return m;
}
}
class B<T>{
private T n;
public void setN(T n){
this.n = n;
}
public T getN(){
return n;
}
}
public static void main(String args[]){
A a = new A();
a.setM(15);
int x = (Integer)a.getM();
a.setM("test");
String y = (String)a.getM();
B<Float> b = new B<Float>();
b.setN(3.14f);
float z = (Float)b.getN();
}
2. 构造方法使用泛型展开目录
class A<T>{
private T value;
public A(T value){
this.value = value;
}
public T getValue(){
return value;
}
}
public static void main(String args[]){
A<String> a = new A<String>("构造方法使用泛型");
System.out.println(a.getValue());
}
3. 指定多个泛型展开目录
class A<T,K>{
private T age;
private K name;
A(T age,K name){
this.age = age;
this.name = name;
}
public T getAge(){
return age;
}
public K getName(){
return name;
}
}
public static void main(String args[]){
A<Integer,String> a = new A<Integer,String>(18,"张三");
System.out.println(a.getName() + a.getAge() + "岁");
}
4. 通配符展开目录
class A<T>{
private T value;
A(T value){
this.value = value;
}
public T getValue(){
return value;
}
public String toString(){
return this.getValue().toString();
}
}
public static void main(String args[]){
A<String> a1 = new A("现在是String类型");
tell(a1);
A<int> a1 = new A(18);
tell(a1);
}
public static void tell(A<?> a){
System.out.println(a)
}
5. 泛型接口展开目录
- JDK1.5 之后也可以声明泛型接口,和声明泛型类的语法类似,在接口名称后加上 <T>
- 格式:
6. 泛型方法展开目录
7. 泛型数组展开目录
public static void main(String args[]){
String arr[] = {"www","wmathor","com"};
tell(arr);
}
public static <T>void tell(T arr[]){
for(int i = 0;i < arr.length;i++){
System.out.println(arr[i]);
}
}