Java泛型编程基础

Wesley13
• 阅读 479

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 objs = Lists.toList(1,"two");

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

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

    The 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.
    
            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. 
            
    * Wildcards with super
    

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

    The quizzical phrase "**? super T**" means that the destination list may have elements of any type that is a supertype of T.
    
    #### The Get and Put Principle
            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.
            public static <T> void copy(List<? super T> dest, List<? extends T> src)
            
    * Wildcards Versus Type Parameters
    

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

     The type "**Collection<?>**" stands for:
    `Collection<? extends Object>`
    Extending Object is one of the most common uses of wildcards, so it makes sense to provide a short form for writing it.
    #### Restrictions on Wildcards
            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).
            
        ```
    List<?> list = new ArrayList<?>(); // compile-time error
    Map<String, ? extends Number> map
    = 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:**

    List<List<?>> lists = new ArrayList<List<?>>();
    lists.add(Arrays.asList(1,2,3));
    lists.add(Arrays.asList("four","five"));
    assert lists.toString().equals("[[1, 2, 3], [four, five]]");
    
    
        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:
    
    
    List<?> list = new ArrayList<Object>(); // ok
    List<?> list = new List<Object>() // compile-time error
    List<?> list = new ArrayList<?>() // compile-time error
    
    点赞
    收藏
    评论区
    推荐文章
    blmius blmius
    2年前
    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
    浪人 浪人
    3年前
    死磕Java泛型(一篇就够)
    Java泛型,算是一个比较容易产生误解的知识点,因为Java的泛型基于擦除实现,在使用Java泛型时,往往会受到泛型实现机制的限制,如果不能深入全面的掌握泛型知识,就不能较好的驾驭使用泛型,同时在阅读开源项目时也会处处碰壁,这一篇就带大家全面深入的死磕Java泛型。泛型擦除初探相信泛型大家都使用过,所以一些基础的知识点就不废话了,以免显得啰嗦。
    Wesley13 Wesley13
    2年前
    java基础知识随身记
    2018年11月12日20:51:35一、基础知识:1、JVM、JRE和JDK的区别:JVM(JavaVirtualMachine):java虚拟机,用于保证java的跨平台的特性。  java语言是跨平台,jvm不是跨平台的。JRE(JavaRuntimeEnvironment):java的运行环境,包括jvmjava的核心类
    Wesley13 Wesley13
    2年前
    java 泛型详解
    对java的泛型特性的了解仅限于表面的浅浅一层,直到在学习设计模式时发现有不了解的用法,才想起详细的记录一下。本文参考java泛型详解、Java中的泛型方法、java泛型详解1\.概述泛型在java中有很重要的地位,在面向对象编程及各种设计模式中有非常广泛的应用。什么是泛型?为什么要使用泛型?泛型,即“参数化类型”。一提到参数,最熟
    浪人 浪人
    3年前
    java 泛型详解-绝对是对泛型方法讲解最详细的,没有之一
    java泛型详解绝对是对泛型方法讲解最详细的,没有之一对java的泛型特性的了解仅限于表面的浅浅一层,直到在学习设计模式时发现有不了解的用法,才想起详细的记录一下。本文参考、、1、概述泛型在java中有很重要的地位,在面向对象编程及各种设计模式中有非常广泛的应用。什么是泛型?
    Wesley13 Wesley13
    2年前
    Java日期时间API系列31
      时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前
    Wesley13 Wesley13
    2年前
    Java泛型详解
    引言Java泛型是jdk1.5中引入的一个新特性,泛型提供了编译时的类型检测机制,该机制允许程序员在编译时检测到非法的类型。泛型是Java中一个非常重要的知识点,在Java集合类框架中泛型被广泛应用。本文我们将从零开始来看一下Java泛型的设计,将会涉及到通配符处理,以及让人苦恼的类型擦除。泛型基础
    Easter79 Easter79
    2年前
    Thinking in java Chapter15 泛型
    1与C比较2简单泛型泛型类3泛型接口4泛型方法5匿名内部类6构建复杂模型78910“泛型”意思就是:适用于许多许多的类型<h2id"1"1与C比较</h2C
    Wesley13 Wesley13
    2年前
    00:Java简单了解
    浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
    可莉 可莉
    2年前
    20175209 《Java程序设计》第八周学习总结
    20175209《Java程序设计》第八周学习总结一、教材知识点总结1.泛型1.泛型类声明:格式classPeople<EPeople是泛型类名称E是泛型列表,可以是任何对象或接口,但不能是基本类型数据