详解Java泛型在类型安全上的应用案例
Java泛型是Java语言中的一种特性,它允许我们在创建类或者方法时,指定类型的集合。这样做的主要目的是提高程序的类型安全性。
以下是一些泛型在类型安全上的应用案例:
- 创建可存储不同类型对象的容器(如List、Map等):
import java.util.List;
import java.util.Map;
public class GenericExample {
// 泛型List,可以存储任何类型的对象
List<String, Integer> stringIntegerList = new ArrayList<>();
// 泛型Map,键为String类型,值为Integer类型
Map<String, Integer> stringIntegerMap = new HashMap<>();
public void addObjectToCollections(Object obj) {
if (obj instanceof String || obj instanceof Integer) {
// 如果对象是字符串或整数类型,直接添加到对应的泛型列表或映射中
if (obj instanceof String) {
stringIntegerList.add(obj);
} else {
stringIntegerMap.put((String) obj), (Integer) obj);
}
} else {
// 如果对象不是字符串或整数类型,抛出异常
throw new IllegalArgumentException("Object type is not supported. Expected: String or Integer.");
}
}
public void displayCollections() {
System.out.println("StringIntegerList:");
for (Object obj : stringIntegerList) {
System.out.print(obj + ": ");
if (obj instanceof String) {
System.out.println(((String) obj)).length());
} else if (obj instanceof Integer) {
System.out.println(((Integer) obj))).intValue());
}
}
System.out.println("\nStringIntegerMap:");
for (Map.Entry<String, Integer>> entry : stringIntegerMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
在这个例子中,我们创建了两个泛型容器:一个泛型List存储包含字符串和整数类型的对象;另一个泛型Map存储键为字符串类型、值为整数类型的对象。
通过在添加对象到容器时进行类型检查和类型转换,我们可以确保程序的类型安全。
还没有评论,来说两句吧...