The Java™ Tutorials — Generics :Why Use Generics? 为什么使用泛型

本文详细阐述了泛型在Java编程中的核心作用,包括如何通过泛型实现更强的类型检查、避免类型转换、以及提升代码复用性和执行泛型算法的能力。通过对比非泛型代码与泛型代码的差异,展示了泛型带来的显著优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Java™ Tutorials — Generics :Why Use Generics? 为什么使用泛型

原文地址:https://docs.oracle.com/javase/tutorial/java/generics/why.html

关键点

  • 泛型具有更强的类型检查
  • 泛型可以避免类型转换
  • 泛型可以泛型算法,增加代码复用性

全文翻译

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

简言之,在定义类、接口和方法时,泛型允许类型(类或者接口)成为参数。非常像在方法声明中人们更为熟悉的正规参数,类型参数为你提供了不同输入下复用同一代码的手段。两种的不同在于对正规参数的输入是具体值,而类型参数的输入却是多种类型。

Code that uses generics has many benefits over non-generic code:

  • Stronger type checks at compile time.

    A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

  • Elimination of casts.The following code snippet without generics requires casting:

    List list = new ArrayList();
    list.add("hello");
    String s = (String) list.get(0);

    When re-written to use generics, the code does not require casting:

    List<String> list = new ArrayList<String>();
    list.add("hello");
    String s = list.get(0); // no cast
  • Enabling programmers to implement generic algorithms. 
    By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.

使用了泛型的代码比不使用泛型的代码相比有更多的优势:

  • 编译时的更强类型检查 
    一个Java编译器会对泛型代码使用强类型检查。如果代码违反了类型安全,编译器就会指出错误。修复编译时错误比修复很难发现的运行时错误更加容易。

  • 消除转换。 
    下面没有使用泛型的代码就需要转换(代码见上),当利用泛型重写如上代码时,代码就无需转换了(代码见上)

  • 允许开发者执行泛型算法。 
    通过使用泛型,开发者可以使用泛型算法。这些算法工作在不同类型的集合上。它们可以被自定义,并且是类型安全的,还具有很好可读性。


下一节: Generic Types
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值