Java泛型编程基础

Java Generics and Collections

  • List< Integer > List< int > The type parameters must always be bound to reference type,not primitive types.

  • One subtlety of boxing and unboxing is that == is defined differently on primitive and on reference types.On type int,int is defined by equality of values,and on type Integer,it is defined by object identify.So both of the following assertions succeed using Sun's JVM:

    List bigs = Arrays.asList(100,200,300); assert sumInteger(bigs) == sum(bigs); assert sumInteger(bigs) != sumInteger(bigs);

  • A further subtlety is that boxed values may be cached.Caching is required when boxing an int or short value between -128 and 127,a char value between '\u0000' and '\u007f',a byte,or a boolean;and caching is permitted when boxing other values.(Like Python)

  • THe foreach loop can be applied to array and any object that implements the interface Iterable,which in turn refers to the interface Iterator.

  • Generic Methods and Varargs Generic methods are indicted by writing at the beginning of the method signature,which declares T as a new type variable.

    class Lists { public static List toList(T[] arr) {...} }

  • vararg feature:Packing the arguments into an array is cumbersome.The vararg feature permits a special,more convenient syntax for the case in which the last argument of a method is an array.To use this feature,replace T[] with T... in the method declaration.

    class Lists { public static List toList(T... arr) {...} }

    • The type parameter to generic method is inferred,but it may also be given explicitly,as is the following examples:

    List ints = Lists.toList(); List

评论

暂无评论