温馨提示:这篇文章已超过239天没有更新,请注意相关的内容是否还可用!
Java中的通配符(Wildcard)是一种用于泛型类型的特殊符号,用于表示未知类型。通配符可以用在泛型类、泛型接口和泛型方法中,用于增加代码的灵活性和可重用性。
通配符使用问号(?)表示,可以用来代替任意类型。通配符可以用作类型参数、方法参数和返回值类型。
下面是一些示例代码,演示了通配符的用法:
1. 通配符作为类型参数:
// 定义一个泛型类,使用通配符作为类型参数
class Box<T> {
private T item;
public void setItem(T item) {
this.item = item;
}
public T getItem() {
return item;
}
}
// 使用通配符作为类型参数实例化泛型类
Box<?> box1 = new Box<>();
box1.setItem("Hello"); // 可以设置任意类型的值
String item1 = (String) box1.getItem(); // 需要进行类型转换
Box<?> box2 = new Box<>();
box2.setItem(10);
Integer item2 = (Integer) box2.getItem();
2. 通配符作为方法参数:
// 定义一个泛型方法,使用通配符作为方法参数
public static void printBox(Box<?> box) {
Object item = box.getItem();
System.out.println(item);
}
// 使用通配符作为方法参数调用泛型方法
Box<String> box1 = new Box<>();
box1.setItem("Hello");
printBox(box1);
Box<Integer> box2 = new Box<>();
box2.setItem(10);
printBox(box2);
3. 通配符作为返回值类型:
// 定义一个泛型方法,使用通配符作为返回值类型
public static Box<?> createBox() {
Box<String> box = new Box<>();
box.setItem("Hello");
return box;
}
// 使用通配符作为返回值类型调用泛型方法
Box<?> box = createBox();
Object item = box.getItem();
System.out.println(item);
通过使用通配符,我们可以在不确定具体类型的情况下,编写更通用的代码。通配符可以用于处理不同类型的对象,提高代码的灵活性和可重用性。