Home  >  Article  >  Java  >  A brief tutorial on Java generics

A brief tutorial on Java generics

黄舟
黄舟Original
2017-02-07 10:33:071082browse

Generics are a feature introduced in Java SE 5.0. Over the years since this language feature appeared, I believe that almost all Java programmers have not only heard of it, but also used it. There are many tutorials about Java generics, free and not free. The best textbooks I have come across are:

  • The Java Tutorial

  • ##Java Generics and Collections, by Maurice Naftalin and Philip Wadler

  • Effective Java Chinese Edition (2nd Edition), by Joshua Bloch.

Although there is so much rich information, sometimes I feel that there is too much of programmers still don’t quite understand the function and significance of Java generics. That's why I wanted to summarize in the simplest form the most basic things a programmer needs to know about Java generics.

The motivation behind Java generics

The easiest way to understand Java generics is to think of them as a convenient syntax that can save you some Java type conversion (casting) operations:

List<Apple> box = ...;
Apple apple = box.get(0);

The above code expresses itself very clearly: box is a List containing Apple objects. The get method returns an Apple object instance, and no type conversion is required in this process. Without generics, the above code needs to be written like this:


List box = ...;
Apple apple = (Apple) box.get(0);

Obviously, the main benefit of generics is to allow the compiler to retain the type information of parameters, perform type checking, and perform type conversion operations: Compiler The absolute accuracy of these type conversions is guaranteed.

Rather than relying on programmers to remember object types and perform type conversions, which can lead to program runtime failures that are difficult to debug and solve, compilers can help programmers force a large number of operations at compile time. Type checking to find errors.

The composition of generics

The composition of generics introduces the concept of a type variable. According to the Java Language Specification, a type variable is an unrestricted identifier that occurs in the following situations:

  • Generic class declaration

  • Generic interface declaration

  • Generic method declaration

  • Generic constructor declaration

Generic classes and interfaces

If a class or interface has one or more type variables, it is generic. Type variables are delimited by angle brackets and placed after the class or interface name:


public interface List<T> extends Collection<T> {
...
}

Simply put, the role of a type variable is like a parameter, which provides information to the compiler for type checking. .



Many classes in the Java class library, such as the entire Collection framework, have been modified to be generic. For example, the List interface we used in the first piece of code above is a generic class. In that code, box is a List object, which is an instance of a class implementation of the List interface with a variable of type Apple. The compiler uses this type variable parameter to automatically perform type conversion when the get method is called and returns an Apple object.


In fact, this new generic tag, or the get method in this List interface is like this:

T get(int index);

The get method actually returns is an object of type T, and T is the type variable in the List declaration.



Generic methods and constructors (Constructor)

are very similar. If one or more types are declared on the method and constructor Variables, they can also be generic.


public static <t> T getFirst(List<T> list)

This method will accept a List type parameter and return an object of type T.



Example

You can either use the generic classes provided in the Java class library or use your own generic classes.


Type-safe writing of data...


The following code is an example. We create a List instance and then load some data:


List<String> str = new ArrayList<String>();
str.add("Hello ");
str.add("World.");

If we try to load another object in List, the compiler will prompt an error:


str.add(1); // 不能编译

Type-safe reading of data...


When we use the List object, it can always guarantee that we get a String object:


String myString = str.get(0);

Traversal in the

class library Many classes, such as Iterator, have enhanced functions and have been genericized. The iterator() method in the List interface now returns Iterator. The object returned by its T next() method does not need to be type converted, and you get the correct type directly.


for (Iterator<String> iter = str.iterator(); iter.hasNext();) {
String s = iter.next();
System.out.print(s);
}


Using foreach

The "for each" syntax also benefits from generics. The previous code can be written like this:


for (String s: str) {
System.out.print(s);
}

This is easy to read and maintain.



Autoboxing and Autounboxing

When using Java generics, the two features of autoboxing/autounboxing will be used automatically, just like the following code:


List<Integer> ints = new ArrayList<Integer>();
ints.add(0);
ints.add(1);
int sum = 0;
for (int i : ints) {
sum += i;
}

However, one thing you need to understand is that encapsulation and decapsulation will bring performance losses, so be cautious in general usage of.

Subtypes

In Java, like other languages ​​with object-oriented types, the type hierarchy can be designed like this:

A brief tutorial on Java generics

在Java中,类型T的子类型既可以是类型T的一个扩展,也可以是类型T的一个直接或非直接实现(如果T是一个接口的话)。因为“成为某类型的子类型”是一个具有传递性质的关系,如果类型A是B的一个子类型,B是C的子类型,那么A也是C的子类型。在上面的图中:

  • FujiApple(富士苹果)是Apple的子类型

  • Apple是Fruit(水果)的子类型

  • FujiApple(富士苹果)是Fruit(水果)的子类型

所有Java类型都是Object类型的子类型。


B类型的任何一个子类型A都可以被赋给一个类型B的声明:

Apple a = ...;
Fruit f = a;

泛型类型的子类型

如果一个Apple对象的实例可以被赋给一个Fruit对象的声明,就像上面看到的,那么,List 和 a List之间又是个什么关系呢?更通用些,如果类型A是类型B的子类型,那C 和 C之间是什么关系?

答案会出乎你的意料:没有任何关系。用更通俗的话,泛型类型跟其是否子类型没有任何关系。

这意味着下面的这段代码是无效的:

List<Apple> apples = ...;
List<Fruit> fruits = apples;

下面的同样也不允许:

List<Apple> apples;
List<Fruit> fruits = ...;
apples = fruits;

为什么?一个苹果是一个水果,为什么一箱苹果不能是一箱水果?

在某些事情上,这种说法可以成立,但在类型(类)封装的状态和操作上不成立。如果把一箱苹果当成一箱水果会发生什么情况?

List<Apple> apples = ...;
List<Fruit> fruits = apples;
fruits.add(new Strawberry());

如果可以这样的话,我们就可以在list里装入各种不同的水果子类型,这是绝对不允许的。

另外一种方式会让你有更直观的理解:一箱水果不是一箱苹果,因为它有可能是一箱另外一种水果,比如草莓(子类型)。

这是一个需要注意的问题吗?

应该不是个大问题。而程序员对此感到意外的最大原因是数组和泛型类型上用法的不一致。对于泛型类型,它们和类型的子类型之间是没什么关系的。而对于数组,它们和子类型是相关的:如果类型A是类型B的子类型,那么A[]是B[]的子类型:

Apple[] apples = ...;
Fruit[] fruits = apples;

可是稍等一下!如果我们把前面的那个议论中暴露出的问题放在这里,我们仍然能够在一个apple类型的数组中加入strawberrie(草莓)对象:

Apple[] apples = new Apple[1];
Fruit[] fruits = apples;
fruits[0] = new Strawberry();

这样写真的可以编译,但是在运行时抛出ArrayStoreException异常。因为数组的这特点,在存储数据的操作上,Java运行时需要检查类型的兼容性。这种检查,很显然,会带来一定的性能问题,你需要明白这一点。

重申一下,泛型使用起来更安全,能“纠正”Java数组中这种类型上的缺陷。

现在估计你会感到很奇怪,为什么在数组上会有这种类型和子类型的关系,我来给你一个《Java Generics and Collections》这本书上给出的答案:如果它们不相关,你就没有办法把一个未知类型的对象数组传入一个方法里(不经过每次都封装成Object[]),就像下面的:

void sort(Object[] o);

泛型出现后,数组的这个个性已经不再有使用上的必要了(下面一部分我们会谈到这个),实际上是应该避免使用。

通配符

在本文的前面的部分里已经说过了泛型类型的子类型的不相关性。但有些时候,我们希望能够像使用普通类型那样使用泛型类型:

  • 向上造型一个泛型对象的引用

  • 向下造型一个泛型对象的引用

向上造型一个泛型对象的引用


例如,假设我们有很多箱子,每个箱子里都装有不同的水果,我们需要找到一种方法能够通用的处理任何一箱水果。更通俗的说法,A是B的子类型,我们需要找到一种方法能够将C类型的实例赋给一个C类型的声明。

为了完成这种操作,我们需要使用带有通配符的扩展声明,就像下面的例子里那样:

List<Apple> apples = new ArrayList<Apple>();
List<? extends Fruit> fruits = apples;

“? extends”是泛型类型的子类型相关性成为现实:Apple是Fruit的子类型,List 是 List extends Fruit> 的子类型。


向下造型一个泛型对象的引用


现在我来介绍另外一种通配符:? super。如果类型B是类型A的超类型(父类型),那么C 是 C super A> 的子类型:

List<Fruit> fruits = new ArrayList<Fruit>();
List<? super Apple> = fruits;


为什么使用通配符标记能行得通?

原理现在已经很明白:我们如何利用这种新的语法结构?


? extends


让我们重新看看这第二部分使用的一个例子,其中谈到了Java数组的子类型相关性:

Apple[] apples = new Apple[1];
Fruit[] fruits = apples;
fruits[0] = new Strawberry();


就像我们看到的,当你往一个声明为Fruit数组的Apple对象数组里加入Strawberry对象后,代码可以编译,但在运行时抛出异常。


现在我们可以使用通配符把相关的代码转换成泛型:因为Apple是Fruit的一个子类,我们使用? extends 通配符,这样就能将一个List对象的定义赋到一个List extends Fruit>的声明上:

List<Apple> apples = new ArrayList<Apple>();
List<? extends Fruit> fruits = apples;
fruits.add(new Strawberry());


这次,代码就编译不过去了!Java编译器会阻止你往一个Fruit list里加入strawberry。在编译时我们就能检测到错误,在运行时就不需要进行检查来确保往列表里加入不兼容的类型了。即使你往list里加入Fruit对象也不行:

fruits.add(new Fruit());

你没有办法做到这些。事实上你不能够往一个使用了? extends的数据结构里写入任何的值。


原因非常的简单,你可以这样想:这个? extends T 通配符告诉编译器我们在处理一个类型T的子类型,但我们不知道这个子类型究竟是什么。因为没法确定,为了保证类型安全,我们就不允许往里面加入任何这种类型的数据。另一方面,因为我们知道,不论它是什么类型,它总是类型T的子类型,当我们在读取数据时,能确保得到的数据是一个T类型的实例:

Fruit get = fruits.get(0);

? super


使用 ? super 通配符一般是什么情况?让我们先看看这个:

List<Fruit> fruits = new ArrayList<Fruit>();
List<? super Apple> = fruits;

我们看到fruits指向的是一个装有Apple的某种超类(supertype)的List。同样的,我们不知道究竟是什么超类,但我们知道Apple和任何Apple的子类都跟它的类型兼容。既然这个未知的类型即是Apple,也是GreenApple的超类,我们就可以写入:

fruits.add(new Apple());
fruits.add(new GreenApple());

如果我们想往里面加入Apple的超类,编译器就会警告你:

fruits.add(new Fruit());
fruits.add(new Object());

因为我们不知道它是怎样的超类,所有这样的实例就不允许加入。

从这种形式的类型里获取数据又是怎么样的呢?结果表明,你只能取出Object实例:因为我们不知道超类究竟是什么,编译器唯一能保证的只是它是个Object,因为Object是任何Java类型的超类。

存取原则和PECS法则

总结 ? extends 和 the ? super 通配符的特征,我们可以得出以下结论:

  • 如果你想从一个数据类型里获取数据,使用 ? extends 通配符

  • 如果你想把对象写入一个数据结构里,使用 ? super 通配符

  • 如果你既想存,又想取,那就别用通配符。

这就是Maurice Naftalin在他的《Java Generics and Collections》这本书中所说的存取原则,以及Joshua Bloch在他的《Effective Java》这本书中所说的PECS法则。

Bloch提醒说,这PECS是指”Producer Extends, Consumer Super”,这个更容易记忆和运用。

以上就是Java泛型简明教程的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn