深入理解Java泛型:类型安全示例

原创 不念不忘少年蓝@ 2024-11-24 01:33 69阅读 0赞

Java泛型是Java语言中的一种特性,它允许我们创建可以处理多种数据类型的类。这样做的主要优点是可以避免运行时类型转换的错误。

以下是一个简单的泛型类和使用它的类型安全示例:

  1. // 定义一个泛型容器类
  2. public class GenericContainer<T> {
  3. private T content;
  4. // 构造器,用于初始化内容
  5. public GenericContainer(T content) {
  6. this.content = content;
  7. }
  8. // 获取内容
  9. public T getContent() {
  10. return content;
  11. }
  12. }
  13. // 类型安全示例:创建一个可以存储任何类型的对象的容器
  14. public class Main {
  15. public static void main(String[] args) {
  16. // 创建不同类型的对象
  17. Integer integer = 10;
  18. String string = "Hello, World!";
  19. List<String> list = new ArrayList<>();
  20. list.add("Item 1");
  21. list.add("Item 2");
  22. // 使用泛型容器来存储这些对象
  23. GenericContainer<T> genericContainer = new GenericContainer<>(integer);
  24. // 在这里,我们尝试将不同类型的对象放入同一个容器中
  25. try {
  26. genericContainer.setContent(string);
  27. System.out.println("String in container: " + genericContainer.getContent()); // 正确输出
  28. // 尝试添加列表到容器
  29. genericContainer.setContent(list);
  30. System.out.println("List in container: " + genericContainer.getContent()); // 输出乱码,因为List是不可变对象,不能放入可变容器中
  31. } catch (ClassCastException e) {
  32. System.out.println("Error: Attempt to store incompatible type in the container.");
  33. }
  34. }
  35. }

在这个示例中,我们创建了一个GenericContainer<T>的实例,并尝试将不同类型的对象添加到容器中。类型安全在这里体现在无法存储不兼容类型的地方会抛出异常。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,69人围观)

还没有评论,来说两句吧...

相关阅读