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

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

你可能感兴趣的:(java,泛型)