10
Java:泛型方法、泛型类、泛型接口、类型通配符
source link: https://blog.51cto.com/mouday/5968659
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Java:泛型方法、泛型类、泛型接口、类型通配符
精选 原创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:泛型
- 打赏
- 赞
- 收藏
- 评论
- 分享
- 举报
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK