Java泛型/泛型限定

一、泛型概述:

  1.来源:1.5jdk出现的新特性;用于解决安全问题,是一个安全机制;

    //下面代码,编译不报错,运行报错,加上泛型给与集合类型限定;

  2.好处:减少运行时的问题,在编译时体现;避免强制转换的麻烦;

  3.关键字:<数据类型>

public class Test {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add("1");
        arrayList.add(1);

        for (Iterator iterator = arrayList.iterator(); iterator.hasNext(); ) {
            String next = (String) iterator.next();
        }
    }
}

二、泛型用法:

  1)泛型类:class 类名<T>

class Base<T> {
    private T t;

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }
}
public class Test {
    public static void main(String[] args) {
        Base<String> s = new Base<String>();
        s.setT("s");
        System.out.println(s.getT());
    }
}

  2)泛型方法:修饰符 <T> 返回值类型 方法名(T t){}

class Demo {
    public <T> void show(T t){
        System.out.println(t);
    }
}
public class Test {
    public static void main(String[] args) {
        Demo demo = new Demo();
        demo.show("string");
        demo.show(123);
    }
}

  3)静态泛型方法:

    //普通方法可以访问类上定义的泛型,但是静态方法不行,静态方法只能自己定义;

    //格式;修饰符 static <T> 返回值类型 方法名(T t){}; <T>千万不能放在static前头;

  4)泛型接口:interface 接口名<T>

interface Inter<T>{
    void show(T t);
}
class InterImpl implements Inter<String> {
    @Override
    public void show(String s) {
        System.out.println(s);
    }
}
public class Test {
    public static void main(String[] args) {
        InterImpl inter = new InterImpl();
        inter.show("s");
    }
}

三、泛型限定:

  1、通配符:?;也可以理解为占位符;

  2、用法:

    1  extends E上限;可以接收E类型或者E的子类型;

    2  super E下限;可以接收E类型或者E的父类型;

三、示例:

import java.util.*;

class Person{

    private String name;

    public Person(String name) {this.name = name;}

    public String getName() { return name;}

  }

class Student extends Person{

    public Student(String name) {super(name); }

}

public class Test {

    public static void main(String[] args) {

        ArrayList<Person> al1=new ArrayList<Person>();

        al1.add(new Person("张三"));

        al1.add(new Person("李四"));

        al1.add(new Person("王五"));

        ArrayList<Student> al2=new ArrayList<Student>();

        al2.add(new Student("刘一"));

        al2.add(new Student("刘二"));

        al2.add(new Student("刘三"));

        

        printAll(al1);

        printAll(al2);

    }

    public static void printAll(ArrayList<? extends Person> al){

        Iterator<? extends Person> it=al.iterator();

        while (it.hasNext()){

            System.out.println(it.next().getName());

        }}}

猜你喜欢

转载自www.cnblogs.com/Tractors/p/11247664.html