Java:泛型方法、泛型类、泛型接口、类型通配符

时间:2022-12-26 12:02:20

(目录)

要求:

JDK >= 1.5

泛型方法

package com.example.demo;

import java.io.IOException;

public class Demo {

    // 泛型方法
    public static <T> void printT(T value) {
        System.out.println(value);
    }

    public static void printObject(Object value) {
        System.out.println(value);
    }

    public static void main(String[] args) throws IOException {
        Demo.printT("Tom");
        Demo.printT(23);

        Demo.printObject("Tom");
        Demo.printObject(23);
    }
}

泛型类

package demo;

public class Box {

    private Object value;

    public void set(Object value) {
        this.value = value;
    }

    public Object get() {
        return this.value;
    }

    public static void main(String[] args) {
        Box box = new Box();
        box.set("Tom");
        String value = (String) box.get();
        System.out.println(value);
    }
}

使用泛型,可以不做类型强制转换

package demo;

public class Box<T> {

    private T value;

    public void set(T value) {
        this.value = value;
    }

    public T get() {
        return this.value;
    }

    public static void main(String[] args) {
        Box<String> box = new Box<>();
        box.set("Tom");
        String value = box.get();
        System.out.println(value);
    }
}

泛型接口

package demo;

interface IBox<T> {

    void set(T value);

    T get();
}


class Box<T> implements IBox<T> {
    private T value;

    @Override
    public void set(T value) {
        this.value = value;
    }

    @Override
    public T get() {
        return this.value;
    }
}

public class Demo {
    public static void main(String[] args) {
        Box<String> box = new Box<>();
        box.set("Tom");
        String value = box.get();
        System.out.println(value);
    }
}

类型通配符

public class Demo {
    public static void main(String[] args) {
        Box<String> box = new Box<>();

        printBox(box);
    }

    public static void printBox(IBox<?> box) {
        System.out.println(box);
    }
}

参考 https://www.runoob.com/java/java-generics.html Java学习路线-7:泛型