泛型(Generics)是一种编程语言特性,允许在定义类、接口和方法时使用类型参数。通过使用泛型,可以提高代码的复用性和类型安全性,减少类型转换和运行时错误。
泛型可以应用于类、接口和方法。以下是一些常见的泛型类型:
List<T>
、Map<K, V>
等,可以存储任意类型的对象。以下是一个简单的泛型类示例:
public class Box<T> {
private T value;
public Box(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
使用示例:
Box<Integer> intBox = new Box<>(123);
System.out.println(intBox.getValue()); // 输出: 123
Box<String> strBox = new Box<>("Hello");
System.out.println(strBox.getValue()); // 输出: Hello
@SuppressWarnings("unchecked")
注解来抑制警告,或者在必要时使用Class<T>
来保留类型信息。public class GenericClass<T> {
private Class<T> clazz;
public GenericClass(Class<T> clazz) {
this.clazz = clazz;
}
public T createInstance() throws Exception {
return clazz.newInstance();
}
}
extends
和super
来解决。public static void printList(List<? extends Number> list) {
for (Number num : list) {
System.out.println(num);
}
}
通过以上内容,你应该对类使用泛型类型有了更深入的了解。如果有更多具体问题,可以进一步探讨。
领取专属 10元无门槛券
手把手带您无忧上云