美文网首页泛型首页投稿(暂停使用,暂停投稿)技术文
《Java编程思想 Generics》读书笔记三——泛型的边界

《Java编程思想 Generics》读书笔记三——泛型的边界

作者: 每天学点编程 | 来源:发表于2016-07-26 06:39 被阅读327次

    Note that using Array.newInstance() is the recommended approach for creating arrays in
    generics.
    ----------------------------开始讲解Bounds---------------------------------

    Bounds(边界)

    Bounds的概念

    Bounds allow you to place constraints on the parameter types that can be used with generics.

    Bounds的作用

    Although this allows you to enforce(强迫) rules about the types that your generics can be applied to, a potentially more important effect is that you can call methods that are in your bound types.
    Because erasure removes type information, the only methods you can call for an unbounded generic parameter are those available for Object.

    Bounds的例子

    以下的例子值得好好琢磨,Java中泛型的边界可以指定多个,当然只能有一个类和多个接口。

    // : generics/BasicBounds.java
    interface HasColor {
        java.awt.Color getColor();
    }
    
    
    class Colored<T extends HasColor> {
        T item;
    
        Colored(T item) {
            this.item = item;
        }
    
        T getItem() {
            return item;
        }
    
        // The bound allows you to call a method:
        java.awt.Color color() {
            return item.getColor();
        }
    }
    
    
    class Dimension {
        public int x, y, z;
    }
    
    
    class Dimension2 {
        public int x, y, z;
    }
    
    
    // This won’t work -- class must be first, then interfaces:
    // class ColoredDimension<T extends HasColor & Dimension> {
    
    
    
    // Multiple bounds:
    class ColoredDimension<T extends Dimension & HasColor> {
        T item;
    
        ColoredDimension(T item) {
            this.item = item;
        }
    
        T getItem() {
            return item;
        }
    
        java.awt.Color color() {
            return item.getColor();
        }
    
        int getX() {
            return item.x;
        }
    
        int getY() {
            return item.y;
        }
    
        int getZ() {
            return item.z;
        }
    }
    
    
    interface Weight {
        int weight();
    }
    
    
    // As with inheritance, you can have only one
    // concrete class but multiple interfaces:
    class Solid<T extends Dimension & HasColor & Weight> {
        T item;
    
        Solid(T item) {
            this.item = item;
        }
    
        T getItem() {
            return item;
        }
    
        java.awt.Color color() {
            return item.getColor();
        }
    
        int getX() {
            return item.x;
        }
    
        int getY() {
            return item.y;
        }
    
        int getZ() {
            return item.z;
        }
    
        int weight() {
            return item.weight();
        }
    }
    
    
    class Bounded extends Dimension implements HasColor, Weight {
        public java.awt.Color getColor() {
            return null;
        }
    
        public int weight() {
            return 0;
        }
    }
    
    
    public class BasicBounds {
        public static void main(String[] args) {
            Solid<Bounded> solid = new Solid<Bounded>(new Bounded());
            solid.color();
            solid.getY();
            solid.weight();
        }
    }
    

    Bounds继承例子

    泛型的边界在继承中只是子类的边界需要更加具体,并且必须遵循父类的边界:

    // : generics/InheritBounds.java
    class HoldItem<T> {
        T item;
    
        HoldItem(T item) {
            this.item = item;
        }
    
        T getItem() {
            return item;
        }
    }
    
    
    class Colored2<T extends HasColor> extends HoldItem<T> {
        Colored2(T item) {
            super(item);
        }
    
        java.awt.Color color() {
            return item.getColor();
        }
    }
    
    
    // Bound mismatch: The type T is not a valid substitute for the bounded parameter <T extends
    // HasColor> of the type Colored2<T>
    // class ColoredDimension2<T extends Dimension> extends Colored2<T> {
    
    
    class ColoredDimension2<T extends Dimension & HasColor> extends Colored2<T> {
        ColoredDimension2(T item) {
            super(item);
        }
    
        int getX() {
            return item.x;
        }
    
        int getY() {
            return item.y;
        }
    
        int getZ() {
            return item.z;
        }
    }
    
    
    class Solid2<T extends Dimension & HasColor & Weight> extends ColoredDimension2<T> {
        Solid2(T item) {
            super(item);
        }
    
        int weight() {
            return item.weight();
        }
    }
    
    
    public class InheritBounds {
        public static void main(String[] args) {
            Solid2<Bounded> solid2 = new Solid2<Bounded>(new Bounded());
            solid2.color();
            solid2.getY();
            solid2.weight();
        }
    }
    

    ----------------------------结束讲解Bounds---------------------------------

    ----------------开始讲解泛型中通配符和边界的区别-------------------------

    泛型中extends?super等的区别

    ?super只能用在泛型类上,而不能在类定义或方法定义上使用。只有extends才能用在方法或类的定义上。
    extends才能定义边界,?superextends等都可以在通配符中使用。
    必须必须明确牢记住这一点。

    import java.util.ArrayList;
    import java.util.List;
    
    class ExtendsClass<T extends String> {
        <T2 extends String> void get() {
    
        }
    
    
        // 不允许
        // 换句话说 super在类定义或方法定义的时候声明泛型的范围
        // <T2 super String> void get2() {
    }
    
    
    // 不允许
    // 换句话说 super在类定义或方法定义的时候声明泛型的范围
    // class SuperClass<T super String> {
    
    
    
    public class ExtendsSuper {
        public static void main(String args[]) {
            List<? super String> str = new ArrayList<String>();
        }
    }
    

    泛型中的通配符出现的原因

    import java.util.ArrayList;
    import java.util.List;
    
    public class GenericNotes {
        public static void main(String args[]) {
    
            // 1.Java的泛型是使用擦除技术实现的,所以, List strList = new ArrayList();显然是肯定可以的
            List<String> strList1 = new ArrayList<String>();
    
    
            // 2.String是Object的子类,所以List<String>应该是等于List<Object>。但是实际上却不是,List<String>表示List类中的属性类型、方法返回值等的类型是String,而List<Object>表示的是Object,很明显这两者不可能是相等的。
            // Type mismatch: cannot convert from ArrayList<String> to List<Object>
            // List<Object> strList2 = new ArrayList<String>();
    
    
    
            // 3.字符串是Java内置的,所以稍有不同
            Object[] objs = new String[10];
        }
    }
    

    如果希望List<String>可以转换为List<Object>要怎么做呢?这就是?等通配符出现的地方
    --------------------结束讲解泛型中通配符和边界的区别-------------------------

    ------------------------开始讲解通配符----------------------------------

    通配符

    必须明确通配符表明的也必须是具体的类型。

    // : generics/GenericsAndCovariance.java
    import java.util.ArrayList;
    import java.util.List;
    
    public class GenericsAndCovariance {
        public static void main(String[] args) {
            // Wildcards allow covariance:
            List<? extends Fruit> flist = new ArrayList<Apple>();
            // Compile Error: can’t add any type of object:
            // flist.add(new Apple());
            // flist.add(new Fruit());
            // flist.add(new Object());
            flist.add(null); // Legal but uninteresting
    
    
            // We know that it returns at least Fruit:
            Fruit f = flist.get(0);
        }
    }
    

    The type of flist is now List<? extends Fruit>, which you can read as "a list of any type that’s inherited from Fruit." This doesn’t actually mean that the List will hold any type of Fruit, however. The wildcard refers to a definite(确切的) type, so it means "some specific type which the flist reference doesn’t specify." So the List that’s assigned has to be holding some specified type such as Fruit or Apple, but in order to upcast to flist, that type is a "don’t actually care.
    这就是通配符的含义,只有使用了通配符才会有所谓的协变性、逆变性。

    通配符和extends

    List<? extends Fruit>表明这是Fruit某个具体子类的List,记住是具体,既然是具体但是你又不知道它是那个具体的子类,你又怎么可以往里面添加对象呢?但是里面保存的对象肯定是Fruit

    通配符和 supe

    List<? super Fruit>表明这是Fruit某个具体父类的List,记住是具体,既然是具体但是你又不知道它是那个具体的父类,你怎么知道List保存的具体是那个父类的对象,或者干脆就是Fruit的子类等类型的对象。

    ------------------------结束讲解通配符----------------------------------

    相关文章

      网友评论

        本文标题:《Java编程思想 Generics》读书笔记三——泛型的边界

        本文链接:https://www.haomeiwen.com/subject/ehkgjttx.html