`

Java: Generics 泛型

阅读更多

Generics allow you to abstract over types
这里的 types 指的是什么?The Java programming language includes classes and interfaces, both are collectively re-ferred to as types. (见附件 Choosing Efficient Inheritance Patterns for Java Generics)

好文一篇 - Java Generics FAQs:
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
Java Tutorials - Generics(Updated):
http://docs.oracle.com/javase/tutorial/java/generics/index.html

Java Tutorials - Generics(老的,看看即可):
http://docs.oracle.com/javase/tutorial/extra/generics/intro.html
http://www.oracle.com/technetwork/articles/javase/generics-136597.html
Java 1.5 Generics Tutorial: How Generics in Java works with Example of Collections, Best practices, Gotchas:
http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html


几个概念:

generic type
引用
A generic type is a generic class or interface that is parameterized over types.

type parameter(also called type variable)
引用
A place holder for a type argument.
Generic types have one or more type parameters.
Each type parameter is replaced by a type argument when an instantiation of the generic type.

By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types

type argument
引用
A reference type or a wildcard that is used for instantiation of a generic type or a reference type used for instantiation of a generic method.  An actual type argument replaces the formal(形式化的) type parameter used in the declaration of the generic type or method.

parameterized type
引用
The instantiation(or invocation) of a generic type with actual type arguments is called a parameterized type

type inference
引用
Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable. The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned. Finally, the inference algorithm tries to find the most specific type that works with all of the arguments.


例子
        /**
         * List & ArrayList 都是 generic type(细说的话,前者是 generic interface, 后者是 generic class)
         * List & Array 类定义上的 <E> 中的 E 为 type parameter(also called type variable)
         * Integer 为 type argument
         * List<Integer> 为 parameterized type
         *
         */
        List<Integer> list = new ArrayList<Integer>();




Generic Methods
Not only types can be generic, but methods can be generic, too. Static and non-static methods as well as constructors can have type parameters. The syntax for declaration of the formal type parameters is similar to the syntax for generic types. The type parameter section is delimited by angle brackets and appears before the method's return type. Its syntax and meaning is identical to the type parameter list of a generic type.


Wildcards(通配符)
http://docs.oracle.com/javase/tutorial/java/generics/subtyping.html
In generic code, the question mark (?), called the wildcard, represents an unknown type, or a family of types. 
There are 3 different flavors of wildcards:
" ? " - the unbounded wildcard. It stands for the family of all types.
" ? extends Type " - a wildcard with an upper bound. It stands for the family of all types that are subtypes of Type , type Type being included.
" ? super Type " - a wildcard with a lower bound. It stands for the family of all types that are supertypes of Type , type Type being included.
PECS (short for Producer extends and Consumer super)
http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs
引用
要站在collection的角度理解 producer & consumer:
当需要 get(从 collection 中取) 时,collection 扮演的是 producer 的角色,所以使用 extends;
当需要 put(往 collection 中放) 时,collection 扮演的是 consumer 的角色,所以使用super。



Bounded Type Parameter 和 upper bounded wildcard 的区别是什么?
http://stackoverflow.com/questions/1750273/what-is-the-difference-between-bounded-wildcard-and-type-parameters?rq=1
http://stackoverflow.com/questions/3486689/java-bounded-wildcards-or-bounded-type-parameter


泛型与继承:
http://www.ibm.com/developerworks/cn/java/j-lo-gj/
引用
在 Java 语言中,我们可以将某种类型的变量赋值给其父类型所对应的变量,例如,String 是 Object 的子类型,因此,我们可以将 String 类型的变量赋值给 Object 类型的变量,甚至可以将 String [ ] 类型的变量(数组)赋值给 Object [ ] 类型的变量,即 String [ ] 是 Object [ ] 的子类型。
上述情形恐怕已经深深地印在了广大读者的脑中,对于泛型来讲,上述情形有所变化,因此请广大读者务必引起注意。为了说明这种不同,我们还是先来分析一个小例子,代码如下所示:
List<String> ls = new ArrayList<String>(); 
	List<Object> lo = ls; 
	lo.add(new Integer()); 
	String s = ls.get(0); 
上述代码的第二行将 List<String>赋值给了 List<Object>,按照以往的经验,这种赋值好像是正确的,因为 List<String>应该是 List<Object>的子类型。这里需要特别注意的是,这种赋值在泛型当中是不允许的! List<String>也不是 List<Object>的子类型。
如果上述赋值是合理的,那么上面代码的第三行的操作将是可行的,因为 lo是 List<Object>,所以向其添加 Integer 类型的元素应该是完全合法的。读到此处,我们已经看到了第二行的这种赋值所潜在的危险,它破坏了泛型所带来的类型安全性。
一般情况下,如果 A 是 B 的子类型,C 是某个泛型的声明,那么 C<A>并不是 C<B>的子类型,我们也不能将 C<A>类型的变量赋值给 C<B>类型的变量。这一点和我们以前接触的父子类型关系有很大的出入,因此请读者务必引起注意。
分享到:
评论

相关推荐

    [Java泛型和集合].(Java.Generics.and.Collections).文字版

    本资料 "[Java泛型和集合].(Java.Generics.and.Collections).Maurice.Naftalin&amp;Philip.Wadler.文字版" 由知名专家Maurice Naftalin和Philip Wadler编著,提供了关于这些主题的深入理解。 **Java泛型** 是自Java...

    深入Java:Generics泛型

    必要性  在程序日益复杂庞大的,编写泛用性代码的价值愈发变得巨大。...但Java引入泛型的初衷,也许只是为了创造 容器类 也说不定。  站在类库设计者的角度,我们不妨走上一遭。  得益于单根

    Java-Generics-and-Collections-Example:Java泛型和集合的示例

    在"Java-Generics-and-Collections-Example-master"这个压缩包中,可能包含了各种关于Java泛型和集合的实例代码,如创建和操作泛型集合、遍历和搜索元素、使用泛型方法等。通过研究这些示例,开发者可以深入理解这两...

    Generics_in_the_Java_Programming_Language译文

    3. 使用泛型:例如 List&lt;Integer&gt; myIntList = new LinkedList()。 泛型的优化: 1. 编译期检查:泛型可以在编译期检查类型的正确性,避免了 ClassCastException。 2. 代码重用:泛型可以将类型参数化,使得代码...

    Java泛型和集合

    Java Generics and Collections 英文版,详细描述java 泛型技术

    java 泛型类的类型识别示例

    在Java编程语言中,泛型(Generics)是一种强大的特性,它允许我们在编写代码时指定容器(如集合)可以存储的数据类型。这提高了代码的安全性和效率,因为编译器可以在编译时检查类型,避免了运行时...

    Java Generics and Collections (Java泛型与集合)

    通过阅读"Java Generics and Collections",开发者不仅可以掌握Java泛型和集合的基本使用,还能深入了解它们的高级特性和最佳实践,从而在实际项目中编写出更高质量的代码。这本书对于Java程序员来说是一份宝贵的...

    Java_Generics_And_Collections__2006.zip_Java Collections

    在Java_Generics_And_Collections__2006.chm文件中,可能包含了以下内容: 1. **泛型的基本使用**:介绍如何声明和使用泛型类、泛型接口和泛型方法。 2. **泛型通配符**:如"? extends T"和"? super T",用于表示...

    java中的泛型样例

    这个压缩包文件"Generics"可能包含了多个示例,用于演示和解释泛型在Java中的应用。 泛型引入于Java 5,它的主要目标是提供编译时的类型检查,避免了类型转换的麻烦,并且能够减少运行时错误。下面我们将详细讨论...

    java中的泛型-详细

    Java中的泛型 JDK1.5 令我们期待很久,可是当他发布的时候却更换版本号为5.0。...而泛型也是一样的,这样写class Java_Generics,V>,这里边的K和V就象方法中的参数str1和str2,也是可变。下面看看例子:

    Java 泛型(Generics)使用说明

    环境:Windows XP Professional、JDK 1.6、Ant 1.7 说明:Java泛型的动机是为解决类型转换在编译时不报错的问题。另外由于“范型编程”(Generic Programming)的推广,于是2004年JDK 5.0引用范型标准。本例子说明...

    Java Generics and Collections

    在Java中,泛型(Generics)引入于J2SE 5.0,目的是提供类型安全的集合,避免了在集合操作中强制类型转换的需要,同时也消除了运行时可能发生的ClassCastException。而集合框架(Collections Framework)是一组接口...

    Java Generics and Collections.chm

    《Java Generics and Collections》是Java开发者必备的参考资料,它深入探讨了Java编程中的泛型(Generics)和集合(Collections)这两个核心概念。在Java编程中,泛型和集合框架是提高代码效率、可读性和类型安全性...

    Java-Generics-and-Collections-2:Java Generics and Collections Java泛型和集合

    泛型与集合 使用 进行初步翻译. 将利用碎片时间进行整理和校对,完整的时间段适合做其他需要大量思考的事,如果你有兴趣欢迎提交PR。 TODO 数据校对 目录 2.4 获取和放置原则 2.5 数组 2.6 通配符与类型参数 2.7 ...

    JavaGenericsBasedBankCardSolution:使用 Java 集合和泛型的银行卡详细信息持有者

    在Java编程语言中,泛型(Generics)是一种强大的特性,它允许我们在编写代码时指定容器(如集合)可以存储的数据类型。这提高了代码的类型安全性,并在编译时就能发现可能的类型错误,而非运行时。在...

    java-generics-collections:Java核心中的泛型和集合

    在有关Java核心的系列文章中,我们将继续学习2个新内容,即Generics和Collection,它们是Java中非常流行的对象。 泛型格式化参数化数据类型,以便我们可以将类,接口或方法用于许多不同的数据类型。 集合只是具有...

    [Java泛型和集合].(Java.Generics.and.Collections).Maurice.Naftalin&Philip.Wadler.文字版

    [Java泛型和集合].(Java.Generics.and.Collections).Maurice.Naftalin&Philip.Wadler.文字版

    Java1.5泛型指南中文版

    Java 1.5 引入的泛型(generics)是一项强大的特性,旨在提升代码的类型安全性、可读性和减少类型转换的繁琐。泛型允许开发者在编程时为类、接口以及方法定义一种或多种类型参数,使得这些类型能够根据实际使用的...

Global site tag (gtag.js) - Google Analytics