`

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)是一种强大的特性,它允许我们在编写代码时指定容器(如集合)可以存储的数据类型。这提高了代码的安全性和效率,因为编译器可以在编译时检查类型,避免了运行时...

    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,它的主要目标是提供编译时的类型检查,避免了类型转换的麻烦,并且能够减少运行时错误。下面我们将详细讨论...

    Java1.5泛型指南中文版

    Java 1.5引入了泛型(Generics)的概念,这是一个重要的语言特性,它允许开发者在编译时期指定集合或其他数据结构中的元素类型,从而避免了运行时期的类型转换错误。通过使用泛型,开发者可以在编程阶段就确保类型的...

    Java深度历险之Java泛型.docx

    Java泛型(Generics)是Java SE 5.0引入的一项重要新特性,它允许开发者在定义类、接口或方法时使用类型参数(Type Parameters)。类型参数在使用时可以用具体的类型来替代。这一特性的引入极大地增强了Java集合框架...

    Java 泛型(Generics)使用说明

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

    Java泛型和集合-英文版

    根据提供的文件信息,我们可以确定本书的标题为《Java泛型和集合》(Java Generics and Collections),作者为Maurice Naftalin和Philip Wadler。该书详细介绍了Java中的泛型(Generics)特性以及集合(Collections...

    java 泛型的使用 详细讲解

    泛型(Generics)是指在面向对象编程中,通过参数化类型来达到类型重用的目的。通俗地说,就是将类或方法中的某些类型定义为参数形式,在实际使用时再传入具体类型的机制。 ##### 2.2 为什么使用泛型? 1. **类型...

    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编程中,泛型和集合框架是提高代码效率、可读性和类型安全性...

Global site tag (gtag.js) - Google Analytics