Java:泛型方法、泛型类、泛型接口、类型通配符
原创
©著作权归作者所有:来自51CTO博客作者彭世瑜的原创作品,请联系作者获取转载授权,否则将追究法律责任
目录
- 泛型方法
- 泛型类
- 泛型接口
- 类型通配符
要求:
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.htmlJava学习路线-7:泛型
聊一聊-JAVA 泛型中的通配符 T,E,K,V,?