Java - 泛型

Java - 泛型,第1张

Java - 泛型

B站黑马视频

泛型

泛型类

package genericity;
public class MyArrayList{
    public void add(E e){
    }
    public void remove(E e){
    }
}

package genericity;
public class GenericityDemo01 {
    public static void main(String[] args) {
        MyArrayList list = new MyArrayList<>();
    }
}

泛型方法

package genericity;

public class GenericityDemo01 {

    public static void main(String[] args) {

        printArray(new String[]{"a","b"});
    }

    public static  void printArray(T[] t){
        StringBuilder sb = new StringBuilder();
        if(t != null){
            sb.append("[");
            for (int i = 0; i < t.length; i++) {
                sb.append(i==t.length-1?t[i]:t[i]+",");
            }
            sb.append("]");
            System.out.println(sb);
        }else{
            System.out.println(t);
        }
    }

}

泛型接口

package genericity;
public class Student {

    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

package genericity;
public interface Date {
    void add(T t);
    void delete(T t);
    void update(T t);
    T queryById(int id);
}

package genericity;
public class StudentDate implements Date{
    @Override
    public void add(Student student) {
    }

    @Override
    public void delete(Student student) {
    }

    @Override
    public void update(Student student) {
    }

    @Override
    public Student queryById(int id) {
        return null;
    }
}


泛型通配符、上下限

package genericity;

import java.util.ArrayList;

public class GenericityDemo {

    public static void main(String[] args) {
        ArrayList benzs = new ArrayList<>();
        benzs.add(new BENZ());
        go(benzs);

        ArrayList bmws = new ArrayList<>();
        bmws.add(new BMW());
        go(benzs);

    }

    public static void go(ArrayList car){

    }
}

class Car{}
class BENZ extends Car{}
class BMW extends Car{}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5691469.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存