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<Integer> 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<E>,which in turn refers to the interface Iterator<E>.

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

    class Lists { public static <T> List<T> 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 <T> List<T> toList(T... arr) {...} }

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

    List<Integer> ints = Lists.<Integer>toList(); List<Object> objs = Lists.<Object>toList(1,"two");

    • List<Integer> is not a subtype of List<Number>,nor is List<Number> a subtype a subtype of List<Integer>;Arrays behave quite differently,with them,Integer[] is a subtype of Number[].
    • Wildcards with extends

interface Collection<E> { ... public boolean addAll(Collection<? extends E> c); ... }

1The phrase "**? extends E**" means that it is also OK to add all members of a collection with elements of any type that is a subtype of E. 2 3 In general, if a structure contains elements with a type of the form ? extends E, we can get elements out of the structure, but we cannot put elements into the structure. 4 5* Wildcards with super

public static <T> void copy(List<? super T> dst, List<? extends T> src) { for (int i = 0; i < src.size(); i++) { dst.set(i, src.get(i)); } }

1The quizzical phrase "**? super T**" means that the destination list may have elements of any type that is a supertype of T. 2 3#### The Get and Put Principle 4 The Get and Put Principle: use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don’t use a wildcard when you both get and put. 5 public static <T> void copy(List<? super T> dest, List<? extends T> src) 6 7* Wildcards Versus Type Parameters

interface Collection<E> { ... public boolean contains(Object o); public boolean containsAll(Collection<?> c); ... }

1 The type "**Collection<?>**" stands for: 2`Collection<? extends Object>` 3Extending Object is one of the most common uses of wildcards, so it makes sense to provide a short form for writing it. 4#### Restrictions on Wildcards 5 Wildcards may not appear at the top level in class instance creation expressions (new) in explicit type parameters in generic method calls, or in supertypes (extends and implements). 6 7 ``` 8List<?> list = new ArrayList<?>(); // compile-time error 9Map<String, ? extends Number> map 10= new HashMap<String, ? extends Number>(); // compile-time error

** Only top-level parameters in instance creation are prohibited from containing wildcards. Nested wildcards are permitted. Hence, the following is legal:**

1List<List<?>> lists = new ArrayList<List<?>>(); 2lists.add(Arrays.asList(1,2,3)); 3lists.add(Arrays.asList("four","five")); 4assert lists.toString().equals("[[1, 2, 3], [four, five]]"); 5 6 7 One way to remember the restriction is that the relationship between wildcards and ordinary types is similar to the relationship between interfaces and classes—wildcards and interfaces are more general, ordinary types and classes are more specific, and instance creation requires the more specific information. Consider the following three statements: 8 9 10List<?> list = new ArrayList<Object>(); // ok 11List<?> list = new List<Object>() // compile-time error 12List<?> list = new ArrayList<?>() // compile-time error
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Java日期时间API系列31

  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前

java基础知识随身记

2018年11月12日20:51:35一、基础知识:1、JVM、JRE和JDK的区别:JVM(JavaVirtualMachine):java虚拟机,用于保证java的跨平台的特性。  java语言是跨平台,jvm不是跨平台的。JRE(JavaRuntimeEnvironment):java的运行环境,包括jvmjava的核心类

java 泛型详解

对java的泛型特性的了解仅限于表面的浅浅一层,直到在学习设计模式时发现有不了解的用法,才想起详细的记录一下。本文参考java泛型详解、Java中的泛型方法、java泛型详解1\.概述泛型在java中有很重要的地位,在面向对象编程及各种设计模式中有非常广泛的应用。什么是泛型?为什么要使用泛型?泛型,即“参数化类型”。一提到参数,最熟