MENU

泛型

June 5, 2018 • Read: 2303 • Java阅读设置

1.认识泛型

  1. 泛型是在JKD1.5之后增加的新功能
  2. 泛型可以解决数据类型的安全性问题,它的主要原理,是在类声明的时候通过一个标识表示类中的某个属性的类型或者某个方法的返回值及参数类型
  3. 泛型不能用基本数据类型,要用其包装类
  4. 格式:
访问权限 class ClassName<泛型,泛型...>{
    属性
    方法
}
  1. 对象的创建
类名称<具体类型> 对象名称 = new 类名称<具体类型>();
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类型
    int x = (Integer)a.getM();
    a.setM("test");//String类型
    String y = (String)a.getM();
    
    B<Float> b = new B<Float>();
    b.setN(3.14f);//Float类型
    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(){//重写toString方法
        return this.getValue().toString();
    }
}
public static void main(String args[]){
    A<String> a1 = new A("现在是String类型");
    tell(a1);//现在是String类型
    A<int> a1 = new A(18);
    tell(a1);//18
}
public static void tell(A<?> a){//?就是通配符,任意类型都可以匹配
    System.out.println(a)
}

5.泛型接口

  1. JDK1.5之后也可以声明泛型接口,和声明泛型类的语法类似,在接口名称后加上<T>
  2. 格式:
interface InterfaceName<T1,...>{
    
}
interface Inter<T>{
    public void say();
}
class A<T> implments Inter<T>{
    public void say(){
        
    }
}
class B implments Inter<String>{
    public void say(){
        
    }
}

6.泛型方法

访问权限 <泛型标识> 泛型标识 方法名称([泛型标识 参数名称])
class A{
    public <T> T tell(T t){
        return t;
    }
}
public static void main(String args[]){
    A a = new A();
    String str = a.tell("泛型方法");
    System.out.println(str);//泛型方法
}

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]);
    }
}
Last Modified: October 19, 2018
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment