国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

(Thinking in Java)第15章 泛型

tinyq / 982人閱讀

摘要:反省發放需要將泛型參數列表之余返回值之前杠桿利用類型參數推斷現在可以了,別。現在可以顯式的類型說明這段代碼沒毛病的,可變參數與泛型方法沒啥好說用于的泛型方法方法可以透明的應用于實現了泛型接口的類。但是這個卻可以指向各種是的對象。

二、簡單泛型 2.一個堆棧類
package tij.generic;

public class Test {
    public static void main(String[] args) {
        LinkedStack lss = new LinkedStack();
        for (String s : "Phasers on stun".split(" "))
            lss.push(s);
        String s;
        while ((s = lss.pop()) != null) {
            System.out.println(s);
        }
    }
}

class LinkedStack {
    private static class Node {
        U item;
        Node next;
        Node() {
            this.item = null;
            this.next = null;
        }
        Node(U item, Node next) {
            this.item = item;
            this.next = next;
        }
        boolean end() {
            return item == null && next == null;
        }
    }
    private Node top = new Node();
    public void push(T item) {
        top = new Node(item, top);
    }
    public T pop() {
        T result = top.item;
        if (!top.end())
            top = top.next;
        return result;
    }
}

在類名后面掛個的意思就是,聲明一下,我這個類里面要用到名字叫做T的泛型啦!

3.RandomList
package tij.generic;

import java.util.ArrayList;
import java.util.Random;

public class Test {
    public static void main(String[] args) {
        RandomList rs = new RandomList<>();
        for (String s : "The quick brown fox jumped over the lazy brown dog"
                .split(" "))
            rs.add(s);
        for (int i = 0; i < 11; i++)
            System.out.print(rs.select() + " ");
    }
}

class RandomList {
    private ArrayList storage = new ArrayList();
    private Random rand = new Random(47);
    public void add(T item) {
        storage.add(item);
    }
    public T select() {
        return storage.get(rand.nextInt(storage.size()));
    }
}
三、泛型接口
package tij.generic;

import java.util.Iterator;
import java.util.Random;

public class Test {
    public static void main(String[] args) {
        CoffeeGenerator gen = new CoffeeGenerator();
        for (int i = 0; i < 5; i++)
            System.out.println(gen.next());
        for (Coffee c : new CoffeeGenerator(5))
            System.out.println(c);
    }
}

interface Generator {
    T next();
}
class Coffee {
    private static long counter = 0;
    private final long id = counter++;
    public String toString() {
        return getClass().getSimpleName() + " " + id;
    }
}

class Mocha extends Coffee {}
class Cappuccino extends Coffee {}
class Latte extends Coffee {}

class CoffeeGenerator implements Generator, Iterable {
    private Class[] types = {Latte.class, Mocha.class, Latte.class};
    private static Random rand = new Random(47);
    public CoffeeGenerator() {

    }
    private int size = 0;
    public CoffeeGenerator(int sz) {
        this.size = sz;
    }
    @Override
    public Iterator iterator() {
        return new CoffeeIterator();
    }

    @Override
    public Coffee next() {
        try {
            return (Coffee) types[rand.nextInt(types.length)].newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    class CoffeeIterator implements Iterator {
        int count = size;
        public boolean hasNext() {
            return count > 0;
        }
        public Coffee next() {
            count--;
            return CoffeeGenerator.this.next();
        }
    }

}
四、泛型方法

對于static方法,無法訪問泛型類的類型參數,所以如果static方法要使用泛型,這個方法就必須是泛型的。
反省發放需要將泛型參數列表之余返回值之前

package tij.generic;

public class Test {
    public  void f(T x){
        System.out.println(x.getClass().getName());
    }
    public static void main(String[] args) {
        Test t=new Test();
        t.f("x");
        t.f(1);
    }
}
1.杠桿利用類型參數推斷
package tij.generic;

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List ls = New.list();
    }
}
class New {
    public static  List list() {
        return new ArrayList();
    }
}


現在可以了,別BB。
現在可以顯式的類型說明

package tij.generic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
    public static void main(String[] args) {
        List ls = New.list();
        f(New.list());
        m(New.map());
    }
    static void f(List x){
        
    }
    static void m(Map> m){
        
    }
}
class New {
    public static  List list() {
        return new ArrayList();
    }
    public static  Map map(){
        return new HashMap();
    }
}

這段代碼沒毛病的,JDK1.8

2.可變參數與泛型方法

沒啥好說

package tij.generic;

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List ls = makeList("A");
        System.out.println(ls);
        ls = makeList("A", "B");
        System.out.println(ls);
    }

    public static  List makeList(T... args) {
        List result = new ArrayList();
        for (T item : args)
            result.add(item);
        return result;
    }
}
3.用于Generator的泛型方法
package tij.generic;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;

public class Test {
    public static void main(String[] args) {
        Collection coffee = Generators.fill(new ArrayList(),
                new CoffeeGenerator(), 4);
        for (Coffee c : coffee) {
            System.out.println(c);
        }
    }
}

class Generators {
    public static  Collection fill(Collection coll, Generator gen,
            int n) {
        for (int i = 0; i < n; i++)
            coll.add(gen.next());
        return coll;
    }

}

interface Generator {
    T next();
}
class Coffee {
    private static long counter = 0;
    private final long id = counter++;
    public String toString() {
        return getClass().getSimpleName() + " " + id;
    }
}

class Mocha extends Coffee {}
class Cappuccino extends Coffee {}
class Latte extends Coffee {}

class CoffeeGenerator implements Generator, Iterable {
    private Class[] types = {Latte.class, Mocha.class, Latte.class};
    private static Random rand = new Random(47);
    public CoffeeGenerator() {

    }
    private int size = 0;
    public CoffeeGenerator(int sz) {
        this.size = sz;
    }
    @Override
    public Iterator iterator() {
        return new CoffeeIterator();
    }

    @Override
    public Coffee next() {
        try {
            return (Coffee) types[rand.nextInt(types.length)].newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    class CoffeeIterator implements Iterator {
        int count = size;
        public boolean hasNext() {
            return count > 0;
        }
        public Coffee next() {
            count--;
            return CoffeeGenerator.this.next();
        }
    }

}

fill方法可以透明的應用于實現了泛型接口的類。

4.一個通用的Generator
package tij.generic;

public class Test {
    public static void main(String[] args) {
        Generator gen = BasicGenerator
                .create(CountedObject.class);
        for (int i = 0; i < 5; i++) {
            System.out.println(gen.next());
        }
    }
}

class CountedObject {
    private static long counter = 0;
    private final long id = counter++;
    public long id() {
        return id;
    }
    public String toString() {
        return "CountedObject " + id;
    }
}

class BasicGenerator implements Generator {
    private Class type;
    public BasicGenerator(Class type) {
        this.type = type;
    }
    public T next() {
        try {
            return type.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static  Generator create(Class type) {
        return new BasicGenerator(type);
    }
}

interface Generator {
    T next();
}

我認為沒什么意義

6.一個Set的實用工具

沒什么卵用

五、匿名內部類與泛型
package tij.generic;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Random;

public class Test {
    static void serve(Teller t, Customer c) {
        System.out.println(t + " serves " + c);
    }
    public static void main(String[] args) {
        Random rand = new Random(47);
        Queue line = new LinkedList();
        Generators.fill(line, Customer.generator(), 15);

        List tellers = new ArrayList();
        Generators.fill(tellers, Teller.generator, 4);
        for (Customer c : line) {
            serve(tellers.get(rand.nextInt(tellers.size())), c);
        }
    }
}

interface Generator {
    T next();
}

class Generators {
    public static  Collection fill(Collection coll, Generator gen,
            int n) {
        for (int i = 0; i < n; i++)
            coll.add(gen.next());
        return coll;
    }

}

class Customer {
    private static long counter = 1;
    private final long id = counter++;
    private Customer() {

    }
    public String toString() {
        return "Customer" + id;
    }

    public static Generator generator() {
        return new Generator() {
            public Customer next() {
                return new Customer();
            }
        };
    }
}

class Teller {
    private static long counter = 1;
    private final long id = counter++;
    private Teller() {

    }
    public String toString() {
        return "Teller " + id;
    }
    public static Generator generator = new Generator() {
        public Teller next() {
            return new Teller();
        }
    };
}
六、構建復雜模型

什么gui東西

七、擦除的神秘之處

自己看書吧

4.邊界的動作
package tij.generic;

import java.lang.reflect.Array;
import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        ArrayMaker stringMaker = new ArrayMaker(String.class);
        String[] stringArray = stringMaker.create(9);
        System.out.println(Arrays.toString(stringArray));
    }
}

class ArrayMaker {
    private Class kind;
    ArrayMaker(Class kind) {
        this.kind = kind;
    }
    T[] create(int size) {
        return (T[]) Array.newInstance(kind, size);
    }
}
八、擦除的補償 2.泛型數組
package tij.generic;

public class Test {
    static final int SIZE = 100;
    static Generic[] gia;
    public static void main(String[] args) {
        gia = (Generic[]) new Object[SIZE];

        gia = (Generic[]) new Generic[SIZE];
        System.out.println(gia.getClass());
        gia[0] = new Generic();

        // gia[1]=new Object();

    }
}

class Generic {}

class ArrayOfGeneric {

}
九、邊界
package tij.generic;

import java.awt.Color;

public class Test {
    public static void main(String[] args) {
        Solid solid = new Solid<>(new Bounded());
        solid.color();
        solid.getY();
        solid.weight();
    }
}

interface HasColor {
    Color getColor();
}
class Colored {
    T item;
    Colored(T item) {
        this.item = item;
    }
    T getItem() {
        return item;
    }
    Color color() {
        return item.getColor();
    }
}

class Dimension {
    public int x, y, z;
}
class ColoredDimension {
    T item;
    ColoredDimension(T item) {
        this.item = item;
    }
    T getItem() {
        return item;
    }
    Color color() {
        return item.getColor();
    }
    int getX() {
        return item.x;
    }
    int getY() {
        return item.y;
    }
    int getZ() {
        return item.z;
    }

}

interface Weight {
    int weight();
}
class Solid {
    T item;
    Solid(T item) {
        this.item = item;
    }
    T getItem() {
        return item;
    }
    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 Color getColor() {
        return null;
    }
    public int weight() {
        return 0;
    }
}

通過上述代碼我可以知道,通過對反省進行集成的限定,可以限制泛型的類型
接下來可以看到如何在繼承的每個層次上添加邊界限制:

package tij.generic;

import java.awt.Color;

public class Test {
    public static void main(String[] args) {
        Solid2 solid = new Solid2<>(new Bounded());
        solid.color();
        solid.getY();
        solid.weight();
    }
}

interface HasColor {
    Color getColor();
}

class HoldItem {
    T item;
    HoldItem(T item) {
        this.item = item;
    }
    T getItem() {
        return item;
    }
}
class Colored2 extends HoldItem {
    Colored2(T item) {
        super(item);
    }
    Color color() {
        return item.getColor();
    }
}

class Dimension {
    public int x, y, z;
}
class ColoredDimension2 extends Colored2 {
    ColoredDimension2(T item) {
        super(item);
    }
    T getItem() {
        return item;
    }
    Color color() {
        return item.getColor();
    }
    int getX() {
        return item.x;
    }
    int getY() {
        return item.y;
    }
    int getZ() {
        return item.z;
    }

}

interface Weight {
    int weight();
}
class Solid2
        extends
            ColoredDimension2 {
    Solid2(T item) {
        super(item);
    }
    int weight() {
        return item.weight();
    }
}

class Bounded extends Dimension implements HasColor, Weight {
    public Color getColor() {
        return null;
    }
    public int weight() {
        return 0;
    }
}

通過上面兩段代碼可以知道,在繼承的過程中,在每個層次上的類型參數都被添加了一定的邊界進行限制。

十、通配符

通配符就是泛型里面的問號,結合eclipse的提示看一下參數類型會對理解這節有很大幫助

package tij.generic;

public class Test {
    public static void main(String[] args) {
        Fruit[] fruit=new Apple[10];
        fruit[0]=new Apple();
        fruit[1]=new Jonathan();
        try{
            fruit[0]=new Fruit();
        }catch(Exception e){
            System.out.println(e);
        }
        try{
            fruit[0]=new Orange();
        }catch(Exception e){
            System.out.println(e);
        }
        
    }
}

class Fruit{}
class Apple extends Fruit{}
class Jonathan extends Fruit{}
class Orange extends Fruit{}

通過以上代碼可以知道,明明是一個apple數組,在接收jonathan對象的時候,編譯器并沒有報錯,而在運行的時候才會報錯,通過泛型,可以將這個錯誤轉化為編譯期的錯誤

List flist = new ArrayList();

這段代碼會報錯

List flist = new ArrayList();

這段代碼不僅不會報錯,而且沒辦法往里傳遞任何信息。但是這個flist卻可以指向各種是fruit的ArrayLIst對象。
因為編譯器并不知道你到底想要啥


如圖,參數類型是null

1.編譯期有多聰明

代碼1:

package tij.generic;

import java.util.Arrays;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List flist = Arrays.asList(new Apple());
        Apple a = (Apple) flist.get(0);
        flist.contains(new Apple());
        flist.indexOf(new Apple());
    }
}

class Fruit {}
class Apple extends Fruit {}
class Jonathan extends Fruit {}
class Orange extends Fruit {}

代碼2:

package tij.generic;

import java.util.Arrays;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        Holder Apple = new Holder(new Apple());
        Apple d = Apple.get();
        Apple.set(d);
        Holder fruit = Apple;
        Fruit p = fruit.get();
        d = (Apple) fruit.get();
        // fruit.set(new Apple());
        fruit.setOb(new Apple());
        System.out.println(fruit.equals(d));
    }
}

class Fruit {}
class Apple extends Fruit {}
class Jonathan extends Fruit {}
class Orange extends Fruit {}

class Holder {
    private T value;
    public Holder() {}
    public Holder(T val) {
        value = val;
    }
    public void set(T val) {
        value = val;
    }
    public void setOb(Object obj) {
        this.value = (T) obj;
    }
    public T get() {
        return value;
    }
    public boolean equals(Object obj) {
        return value.equals(obj);
    }
}
2.逆變

代碼1:

package tij.generic;

import java.util.List;

public class Test {
    public static void main(String[] args) {}
}

class Fruit {}
class Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}

class SuperTypeWildcards {
    static void writerTo(List apples) {
        apples.add(new Apple());
        apples.add(new Jonathan());
        // apples.add(new Fruit());
    }
}

? super Apple的意思就是,只要是Apple或者Apple的爹的意思,但事實上,正如上面所說,編譯器并不知道你這個通配符代表的是什么,


但是在super這里,至少所有的apple和apple的子類,全都是apple,這沒錯的。

代碼3:

package tij.generic;

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        GenericWriting.f1();
        GenericWriting.f2();
    }
}

class Fruit {}
class Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}

class GenericWriting {
    static  void writeExact(List list, T item) {
        list.add(item);
    }
    static List apples = new ArrayList();
    static List fruit = new ArrayList();
    static void f1() {
        writeExact(apples, new Apple());
        writeExact(fruit, new Apple());
        fruit.add(new Apple());
    }

    static  void writeWithWildcard(List list, T item) {
        list.add(item);
    }
    static void f2() {
        writeWithWildcard(apples, new Apple());
        writeWithWildcard(fruit, new Apple());
    }
}

其實是可以的,書上說不可以

代碼3:

package tij.generic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        GenericWriting.f1();
        GenericWriting.f2();
        GenericWriting.f3();
    }
}

class Fruit {}
class Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}

class GenericWriting {

    static List apples = Arrays.asList(new Apple());
    static List fruit = Arrays.asList(new Fruit());

    static  T readExact(List list) {
        return list.get(0);
    }
    static void f1() {
        Apple a = readExact(apples);
        Fruit f = readExact(fruit);
        f = readExact(apples);
    }

    static class Reader {
        T readExact(List list) {
            return list.get(0);
        }
    }
    static void f2() {
        Reader fruitReader = new Reader();
        Fruit f = fruitReader.readExact(apples);// error
    }
    static class CovariantReader {
        T readCovariant(List list) {
            return list.get(0);
        }
    }
    static void f3() {
        CovariantReader fruitReader = new CovariantReader();
        Fruit f = fruitReader.readCovariant(fruit);
        Fruit a = fruitReader.readCovariant(apples);

        CovariantReader appleReader = new CovariantReader();
        Apple ap = appleReader.readCovariant(apples);
    }
}

這是一次對比

3.無界通配符
class Wildcards{
    static void rawArgs(Holder holder,Object arg){
        holder.set(arg);
        holder.set(new Wildcards());
//        T t=holder.get();
//        Error
        Object obj=holder.get();
    }
    
    static void unboundedArg(Holder holder,Object arg){
//        holder.set(arg);
//        holder.set(new Wildcards());
//        Error
        Object obj=holder.get();
    }
    
    static  T exact1(Holder holder){
        T t=holder.get();
        return t;
    }
    static  T exact2(Holder holder,T arg){
        holder.set(arg);
        T t=holder.get();
        return t;
    }
    static  T wildSubtype(Holder holder,T arg){
//        holder.set(arg);
        T t=holder.get();
        return t;
    }
    static  void wildSupertype(Holder holder,T arg){
        holder.set(arg);
//        T t=holder.get();
        Object obj=holder.get();
    }
} 

破事兒真多,這玩意記不過來,邊用邊記吧,
書上看看得了

4.類型轉換
package tij.generic;

public class Test {
    static  void f1(Holder holder) {
        T t = holder.get();
        System.out.println(t.getClass());
    }
    static void f2(Holder holder) {
        f1(holder);

    }
    public static void main(String[] args) {
        Holder raw = new Holder(1);
        f2(raw);
        f1(raw);
    }
}

class Holder {
    private T value;
    public Holder() {}
    public Holder(T val) {
        value = val;
    }
    public void set(T val) {
        value = val;
    }
    public T get() {
        return value;
    }
    public boolean equals(Object obj) {
        return value.equals(obj);
    }
}
十一、問題 1.任何基本類型都不能作為類型參數 2.實現參數化接口
interface Payable{}
class Employee implements Payable{}
class Hourly extends Employee implements Payable{    
}
3、轉型和警告
package tij.generic;

public class Test {
    public static final int SIZE = 10;
    public static void main(String[] args) {
        FixedSizeStack strings = new FixedSizeStack(SIZE);
        for (String s : "A B C D E F G H I J".split(" "))
            strings.push(s);
        for (int i = 0; i < SIZE; i++) {
            String s = strings.pop();
            System.out.print(s + " ");
        }
    }
}

class FixedSizeStack {
    private int index = 0;
    private Object[] storage;
    public FixedSizeStack(int size) {
        storage = new Object[size];
    }
    public void push(T item) {
        storage[index++] = item;
    }
    public T pop() {
        return (T) storage[--index];
    }
}
4.重載 5.基類劫持了接口 十二、自限定的類型 1.古怪的循環泛型
class GenericType{}
class CuriouslyRecurringGeneric extends GenericType{
    
}
2.自限定
package tij.generic;

public class Test {
    public static void main(String[] args) {
        BasicOther b = new BasicOther();
        BasicOther b2 = new BasicOther();
        b.set(new Other());
        Other other = b.get();
        b.f();
    }
}

class BasicHolder {
    T element;
    void set(T arg) {
        element = arg;
    }
    T get() {
        return element;
    }
    void f() {
        System.out.println(element.getClass());
    }
}


class Other {}
class BasicOther extends BasicHolder {}
package tij.generic;

public class Test {
    public static void main(String[] args) {
        A a = new A();
        a.set(new A());
        a = a.set(new A()).get();
        a = a.get();
        B b = new B();
        b.set(a);
        a = b.get();
        C c = new C();
        c = c.setAndGet(new C());

    }
}

class BasicHolder {
    T element;
    void set(T arg) {
        element = arg;
    }
    T get() {
        return element;
    }
    void f() {
        System.out.println(element.getClass());
    }
}

class SelfBounded> {
    T element;
    SelfBounded set(T arg) {
        this.element = arg;
        return this;
    }
    T get() {
        return element;
    }
}

class A extends SelfBounded {}
class B extends SelfBounded {}
class C extends SelfBounded {
    C setAndGet(C arg) {
        set(arg);
        return get();
    }
}
class D {}
class E extends SelfBounded {}
class F extends SelfBounded {}
3.參數協變
class Base{}
class Derived extends Base{}
interface OrdinaryGetter{
    Base get();
}
interface DerivedGetter extends OrdinaryGetter{
    Derived get();
}

重寫方法

interface GenericGetter> {
    T get();
}
interface Getter extends GenericGetter {}
class GenericsAndReturnTypes {
    void test(Getter g) {
        Getter result = g.get();
        GenericGetter gg = g.get();
    }
}

自限定泛型

class OrdinarySetter{
    void set(Base base){
        System.out.println("OrdinarySetter.set(Base)");
    }
}
class DerivedSetter extends OrdinarySetter{
    void set(Derived derived){
        System.out.println("DerivedSetter.set(Derived)");
    }
}

這是重載,不是重寫

interface SelfBoundSetter>{
    void set(T arg);
}

interface Setter extends SelfBoundSetter{}
class SelfBoundingAndCovariantArguments{
    void testA(Setter s1,Setter s2,SelfBoundSetter sbs){
        s1.set(s2);
        s1.set(sbs);
    }
}
十三、動態類型安全
package tij.generic;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
    @SuppressWarnings("unchecked")
    static void oldStyleMethod(List probablyLatte) {
        probablyLatte.add(new Cappuccino());
    }
    public static void main(String[] args) {
        List latte = new ArrayList();
        oldStyleMethod(latte);

        List latte2 = Collections.checkedList(new ArrayList(),
                Latte.class);
        oldStyleMethod(latte2);

    }
}

class Coffee {}
class Latte extends Coffee {}
class Cappuccino extends Coffee {}
十四、異常
package tij.generic;

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        ProcessRunner runner = new ProcessRunner();
        for (int i = 0; i < 3; i++)
            runner.add(new Processor1());

        try {
            runner.processAll();
        } catch (Failure1 e) {
            // TODO Auto-generated catch block
            System.out.println(e);
        }

        ProcessRunner runner2 = new ProcessRunner();
        for (int i = 0; i < 3; i++)
            runner2.add(new Processor2());

        try {
            runner2.processAll();
        } catch (Failure2 e) {
            // TODO Auto-generated catch block
            System.out.println(e);
        }
    }
}

interface Processor {
    void process(List resultCollector) throws E;
}
class ProcessRunner extends ArrayList> {
    List processAll() throws E {
        List resultCollector = new ArrayList();
        for (Processor processor : this) {
            processor.process(resultCollector);
        }
        return resultCollector;

    }
}

class Failure1 extends Exception {}
class Processor1 implements Processor {
    static int count = 3;
    @Override
    public void process(List resultCollector) throws Failure1 {
        if (count-- > 1)
            resultCollector.add("Hep!");
        else
            resultCollector.add("Ho!");
        System.out.println(resultCollector);
        if (count < 0) {
            throw new Failure1();
        }

    }
}

class Failure2 extends Exception {}
class Processor2 implements Processor {
    static int count = 2;
    @Override
    public void process(List resultCollector) throws Failure2 {
        if (count-- == 0)
            resultCollector.add(47);
        else
            resultCollector.add(11);
        System.out.println(resultCollector);
        if (count < 0)
            throw new Failure2();
    }

}

說實話,這有什么卵意義么

十五、混型 2.與接口混合
package tij.generic;

import java.util.Date;

public class Test {
    public static void main(String[] args) {
        Mixin mixin1 = new Mixin(), mixin2 = new Mixin();
        mixin1.set("test string 1");
        mixin2.set("test string 2");
        System.out.println(mixin1.get() + " " + mixin1.getStamp() + " "
                + mixin1.getSerialNumber());
        System.out.println(mixin2.get() + " " + mixin2.getStamp() + " "
                + mixin2.getSerialNumber());
    }
}

interface TimeStamped {
    long getStamp();
}
class TimeStampedImp implements TimeStamped {
    private final long timeStamp;
    public TimeStampedImp() {
        super();
        this.timeStamp = new Date().getTime();
    }
    public long getStamp() {
        return this.timeStamp;
    }
}

interface SerialNumbered {
    long getSerialNumber();
}

class SerialNumberedImp implements SerialNumbered {
    private static long counter = 1;
    private final long serialNumber = counter++;
    public long getSerialNumber() {
        return serialNumber;
    }
}

interface Basic {
    void set(String val);
    String get();
}

class BasicImp implements Basic {
    private String value;
    public void set(String val) {
        value = val;
    }
    public String get() {
        return value;
    }
}

class Mixin extends BasicImp implements TimeStamped, SerialNumbered {
    private TimeStamped timeStamp = new TimeStampedImp();
    private SerialNumbered serialNumber = new SerialNumberedImp();
    @Override
    public long getSerialNumber() {
        return serialNumber.getSerialNumber();
    }

    @Override
    public long getStamp() {
        return timeStamp.getStamp();
    }

}
3.使用裝飾器模式
package tij.generic;

import java.util.Date;

public class Test {
    public static void main(String[] args) {
        TimeStamped t = new TimeStamped(new Basic());
        TimeStamped t2 = new TimeStamped(new SerialNumbered(new Basic()));
        
        
        SerialNumbered s = new SerialNumbered(new Basic());
        SerialNumbered s2 = new SerialNumbered(new TimeStamped(new Basic()));
    }
}

class Basic {
    private String value;
    void set(String val) {
        this.value = val;
    };
    String get() {
        return value;
    };
}

class Decorator extends Basic {
    protected Basic basic;
    public Decorator(Basic basic) {
        this.basic = basic;
    }
    public void set(String val) {
        basic.set(val);
    }
    public String get() {
        return basic.get();
    }
}

class TimeStamped extends Decorator {
    private final long timeStamp;
    public TimeStamped(Basic basic) {
        super(basic);
        this.timeStamp = new Date().getTime();
    }
    public long getStamp() {
        return this.timeStamp;
    }
}

class SerialNumbered extends Decorator {
    public SerialNumbered(Basic basic) {
        super(basic);
    }
    private static long counter = 1;
    private final long serialNumber = counter++;
    public long getSerialNumber() {
        return serialNumber;
    }
}
十六、潛在類型機制

之后pass不看了,費勁

end

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/67607.html

相關文章

  • Thinking in Java11 持有對象

    摘要:迭代器解決了這個問題。刪除后于是我們可以寫一個方法,接受一個類型,然后讓他調用方法,這就不需要考慮這個是個還是了,也就是說,可以將遍歷容器的操作與序列底層的結構分離,迭代器統一了對容器類的訪問方式。十二和兩種遍歷的方法,與迭代器方法。 一、泛型和類型安全的容器 package tij.hoding; import java.util.ArrayList; public class ...

    v1 評論0 收藏0
  • Thinking in Java13 字符串

    摘要:四上的操作看五格式化輸出運用和語言很相似和是等價的喲類格式化說明符轉換六正則表達式網上教程學七掃描輸入新增了類。 一、不可變String String類型的對象是不可變的,所有的改變實際上都是創建了一個新的String對象,另外當String作為傳入參數的時候,其實實際上傳入的是這個引用的一個拷貝,這個方法結束了之后這個傳入的引用也就消失了,原來的那個String不會受到方法內的影響而...

    feng409 評論0 收藏0
  • Thinking in Java14 類型信息

    摘要:通過運行時類型信息,程序能夠使用基類的指針或引用來檢查這些指針或引用所指的對象的實際派生類型。編程應該盡量面向接口編程,應該對類型信息盡量的少了解二對象看書,書上寫得好靜態語句塊在這個類被加載的時候運行。 一、為什么需要RTTI Run-Time Type Information。通過運行時類型信息,程序能夠使用基類的指針或引用來檢查這些指針或引用所指的對象的實際派生類型。編程應該盡量...

    tomorrowwu 評論0 收藏0
  • Thinking in Java10 內部類

    摘要:內部類中也可以取得這個外部類對象引用。創建成員內部類對象的時候需要外部類對象。另外在方法中的內部類不能加等權限修飾符,只能加和修飾符。可以在接口內部定義內部類,而且他們即使沒有修飾,也會自動變成的。 Thinking in Java撈干貨,寫筆記 一、成員內部類 1.最基本使用 public class Demo { class Contents{ privat...

    Brenner 評論0 收藏0
  • 《On Java 8》中文版,又名《Java 編程思想》中文五版

    摘要:基于版本基于版本。由于中英行文差異,完全的逐字逐句翻譯會很冗余啰嗦。譯者在翻譯中同時參考了谷歌百度有道翻譯的譯文以及編程思想第四版中文版的部分內容對其翻譯死板,生造名詞,語言精煉度差問題進行規避和改正。 來源:LingCoder/OnJava8 主譯: LingCoder 參譯: LortSir 校對:nickChenyx E-mail: 本書原作者為 [美] Bru...

    BingqiChen 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<