关于java泛型的使用方式。。。。

转自:http://onewebsql.com/blog/generics-extends-super

以下基本够用了

Today we continue our mini-series on Java Generics. In previous posts we have investigated

Java type parameters are used as type placeholders.

?


1

public class List<X>  { }

List<X> is a container for X objects, and X can be instantiated with any class: you can haveList<Object>List<String>, and List<Number>.

Introducing bounds: extends

You often want to restrict the set of types that can be used in instantiation. If you create a class Garage, you want it to hold only Vehicle objects.

The syntax you use in Java is like this:

?


1

public class Garage<X extends Vehicle> { }

Every time you instantiate the Garage, the type parameter has to be a subclass of Vehicle.

?


1

2

3

class Car extends Vehicle { }

class Motorcycle extends Vehicle { }

class Fruit extends Object { }

Thus Garage<Car> and Garage<Motorcycle> are OK but Garage<Fruit> is not OK.

You can specify more than one bound with extends:

?


1

2

3

4

class Vehicle { }

interface PassengerVehicle { }

interface MotorVehicle { }

class ParkingGarage<X extends Vehicle & MotorVehicle & PassengerVehicle>

You can specify at most one class in the bound (obviously, as you can only inherit from one class in Java) and as many interfaces as you want.

The bound can refer to the typing parameter:

?


1

class BST<X extends Comparable<X>> {}

BST class can only be instantiated with classes X which implement the Comparable<X>interface.

Bounds in method parameters

Java method can be parametrized, too. The syntax is as follows:

?


1

<T> T getRandomElement(List<T> list) {}

As with class definitions, you often want to restrict the type parameter in the method. A method which takes a list of Vehicles and returns the fastest vehicle in the list can have the following type.

?


1

<T extends Vehicle> T getFastest(List<T> list) { }

You can pass as argument a list of any vehicles. List<Car> is OK, List<Motorcycle> is OK, List<Vehicle> is OK, too. List<Number> is not OK.

Note that the following declaration wouldn‘t do the trick.

?


1

Vehicle getFastest2(List<Vehicle> list) { }

The argument to the method getFastest2 has to be exactly a List<Vehicle>, and not aList<Car>, because List<Car> is not a subtype of List<Vehicle>,

Wilcards

Take a look at the following declaration.

?


1

<T extends Vehicle> int totalFuel(List<T> list) { }

The parameter T occurs only once in the method signature, in an argument. You can imagine that the method body does not use the name T either. In this case you can use an alternative syntax, called wildcards, denoted with ?:

?


1

int totalFuel(List<? extends Vehicle> list) { }

The two signatures for totalFuel are equivalent. The meaning of <? extends Vehicle> is: I don‘t care what the type parameter is, as long as it is a subclass of Vehicle.

Introducing bounds: super

There is also dual bound, called super. As you guess it is used to denote that you can pass only superclasses of the bound. There are some differences between extends and super, though.

You can‘t use super in class declaration

The super bound is not allowed in class definition.

?


1

2

//this code does not compile !

class Forbidden<X super Vehicle> { }

Why? Because such construction doesn‘t make sense. For example, you can‘t erase the type parameter with Vehicle because the class Forbidden could be instantiated with Object. So you have to erase type parameters to Object anyway. If think about class Forbidden<Object>, it can take any value in place of Xnot only superclasses of Vehicle. There‘s no point in using super bound, it wouldn‘t get us anything. Thus it is not allowed.

Wildcards

The syntax for wildcards is also similar to extends:

?


1

int totalValue(Valuer<? super Vehicle> valuer)

The method has to take a comparator which is able to compare Vehicles. If it comparesObjects as well, that‘s fine too.

When to use extends and super

Wildcards are most useful in method parameters. They allow for the necessary flexibility in method interfaces.

People are often confused when to use extends and when to use super bounds. The rule of thumb is the get-put principle. If you get something from a parametrized container, useextends.

?


1

2

3

4

5

6

7

int totalFuel(List<? extends Vehicle> list) {

    int total = 0;

    for(Vehicle v : list) {

        total += v.getFuel();

    }

    return total;

}

The method totalFuel gets Vehicles from the list, asks them about how much fuel they have, and computes the total.

If you put objects into a parametrized container, use super.

?


1

2

3

4

5

6

7

int totalValue(Valuer<? super Vehicle> valuer) {

    int total = 0;

    for(Vehicle v : vehicles) {

        total += valuer.evaluate(v);

    }

    return total;

}

The method totalValue puts Vehicles into the Valuer.

It‘s useful to know that extends bound is much more common than super.

One more tip: if you are intimidated by wildcards (which is natural in the beginning), try to write the explicitly parametrized version first. In typical usage the two versions are equivalent. Eventually, you‘ll figure out when you can get rid of type parameters and use wildcards.

时间: 2024-10-18 03:38:51

关于java泛型的使用方式。。。。的相关文章

Java——泛型(最易懂的方式讲解泛型)

来自:代码大湿代码大湿 写在前面: 只要认真看过,基本能很熟悉泛型的特性.泛型是JDK1.5之后出现的,比如JDK1.5之前的ArrayList,会出现2个问题 1:向ArrayList当中添加对象,添加String和Date都可以,但我们的本意是添加String,编译器不会检查错误,会导致不可预知的错误. 2:get()方法得到一个元素的时候要进行强制类型转换.所以泛型的引入很好的解决了这2个问题. 注:泛型把错误(异常)抛到编译时期. 1,泛型类 一个泛型类如下; class Pair<T,

JAVA泛型详解——转

泛型(Generic type 或者generics)是对 Java 语言的类型系统的一种扩展,以支持创建可以按类型进行参数化的类.可以把类型参数看作是使用参数化类型时指定的类型的一个占位符,就像方法的形式参数是运行时传递的值的占位符一样. 可以在集合框架(Collection framework)中看到泛型的动机.例如,Map类允许您向一个Map添加任意类的对象,即使最常见的情况是在给定映射(map)中保存某个特定类型(比如String)的对象. 因为Map.get()被定义为返回Object

1月21日 - (转)Java 泛型

java泛型 什么是泛型? 泛型(Generic type 或者 generics)是对 Java 语言的类型系统的一种扩展,以支持创建可以按类型进行参数化的类.可以把类型参数看作是使用参数化类型时指定的类型的一个占位符,就像方法的形式参数是运行时传递的值的占位符一样. 可以在集合框架(Collection framework)中看到泛型的动机.例如,Map 类允许您向一个 Map 添加任意类的对象,即使最常见的情况是在给定映射(map)中保存某个特定类型(比如 String)的对象. 因为 M

java泛型的讲解

java泛型 什么是泛型? 泛型(Generic type 或者 generics)是对 Java 语言的类型系统的一种扩展,以支持创建可以按类型进行参数化的类.可以把类型参数看作是使用参数化类型时指定的类型的一个占位符,就像方法的形式参数是运行时传递的值的占位符一样. 可以在集合框架(Collection framework)中看到泛型的动机.例如,Map 类允许您向一个 Map 添加任意类的对象,即使最常见的情况是在给定映射(map)中保存某个特定类型(比如 String)的对象. 因为 M

Java 泛型 Java使用泛型的意义

Java 泛型 Java使用泛型的意义 @author ixenos 直接意义 在编译时保证类型安全 根本意义 a) 类型安全问题源自可复用性代码的设计,泛型保证了类型安全的复用模板 b) 使用复用性模板时不用手动强制类型转换 三种泛型实现方式的优缺点 C++:模板方式实现,在编译时完全展开并且支持偏特化,类型精度高,代码共享差: Java 5:擦除方式实现,仅用于编译时类型检查,在运行时擦除,向后兼容性好,代码共享好,类型精度非常差: C# 2.0:混合方式实现,在运行时展开特化,类型精度高,

Java泛型简明教程

Java泛型简明教程 博客分类: Java综合 JavaApple数据结构CC++ Java泛型简明教程 本文是从 Java Generics Quick Tutorial 这篇文章翻译而来. 泛型是Java SE 5.0中引入的一项特征,自从这项语言特征出现多年来,我相信,几乎所有的Java程序员不仅听说过,而且使用过它.关于Java泛型的教程,免费的,不免费的,有很多.我遇到的最好的教材有: The Java Tutorial Java Generics and Collections ,

Java泛型-- 通配符

转自:http://blog.csdn.net/flfna/article/details/6576394 ———————————————————————————————————————————— 通配符 在本文的前面的部分里已经说过了泛型类型的子类型的不相关性.但有些时候,我们希望能够像使用普通类型那样使用泛型类型: ◆ 向上造型一个泛型对象的引用 ◆ 向下造型一个泛型对象的引用 向上造型一个泛型对象的引用 例如,假设我们有很多箱子,每个箱子里都装有不同的水果,我们需要找到一种方法能够通用的处

java泛型(二)、泛型的内部原理:类型擦除以及类型擦除带来的问题

java泛型(二).泛型的内部原理:类型擦除以及类型擦除带来的问题 参考:java核心技术 一.Java泛型的实现方法:类型擦除 前面已经说了,Java的泛型是伪泛型.为什么说Java的泛型是伪泛型呢?因为,在编译期间,所有的泛型信息都会被擦除掉.正确理解泛型概念的首要前提是理解类型擦出(type erasure). Java中的泛型基本上都是在编译器这个层次来实现的.在生成的Java字节码中是不包含泛型中的类型信息的.使用泛型的时候加上的类型参数,会在编译器在编译的时候去掉.这个过程就称为类型

Java 泛型的约束与局限性

Java 泛型的约束与局限性 @author ixenos 不能用基本类型实例化类型参数 不能用类型参数代替基本类型:例如,没有Pair<double>,只有Pair<Double>,其原因是类型擦除.擦除之后,Pair类含有Object类型的域,而Object不能存储double值.这体现了Java语言中基本类型的独立状态. 运行时类型查询只适用于原始类型(raw type) 运行时:通常指在Classloader装载之后,JVM执行之时 类型查询:instanceof.getC