java 萬用字元的使用-upcast

來源:互聯網
上載者:User

標籤:

package localevidence;//: generics/UnboundedWildcards1.java//: generics/CovariantArrays.javaclass Fruit {}class Appleee extends Fruit {}class Jonathan extends Appleee {}class Orange extends Fruit {}public class Testwildcats {public static void main(String[] args) {Fruit[] fruit = new Appleee[10];fruit[0] = new Appleee(); // OKfruit[1] = new Jonathan(); // OK// Runtime type is Appleee[], not Fruit[] or Orange[]:try {// Compiler allows you to add Fruit:fruit[0] = new Fruit(); // ArrayStoreException} catch(Exception e) { System.out.println(e); }try {// Compiler allows you to add Oranges:fruit[0] = new Orange(); // ArrayStoreException} catch(Exception e) { System.out.println(e); }}} /* Output:java.lang.ArrayStoreException: Fruitjava.lang.ArrayStoreException: Orange*///:~
Fruit[] fruit = new Appleee[10];// 這是執行個體化fruit數組為appleee類型

  但是編譯沒有錯誤,但是在runtime的時候為啥報錯呢?

This makes sense to the compiler, because it has a Fruit[] reference—why shouldn’t it allow a Fruit 

object, or anything descended from Fruit, such as Orange, to be placed into the array? So at compile time, this is allowed.

因為這對瀏覽器來說這是合理的,因為

Fruit[] fruit = new Appleee[10];
// Compiler allows you to add Fruit:fruit[0] = new Fruit(); // ArrayStoreException

它有一個Fruit[]類型的申明,為啥不可以將Fruit 變數賦值給它呢,或者繼承Fruit的子類呢?可以的編譯器認為沒有問題。

 The runtime array mechanism, however, knows that it’s dealing with an Apple [] and throws an exception when a foreign type is placed into the array.

但是runtime 運行機制卻認為她是在處理Appleee[]類型的,所以如果你放入其它類型的就會報錯。
"Upcast" is actually rather a misnomer here. What you’re really doing is assigning one array
to another.

"向上轉型"事實上並不是不當,你實際在做的是將一種類型的數組賦值給另外一個數組。

 The array behavior is that it holds other objects, but because we are able to
upcast, it’s clear that the array objects can preserve the rules about the type of objects they
contain. It’s as if the arrays are conscious of what they are holding, so between the compile time checks and the runtime checks, you can’t abuse them.
This arrangement for arrays is not so terrible, because you do find out at run time that you’ve
inserted an improper type. But one of the primary goals of generics is to move such error
detection to compile time. So what happens when we try to use generic containers instead of
arrays?
The real issue is that we are talking about the type of the container, rather than the type that
the container is holding.
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."

package localevidence;public class Holder<T> { 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); } public static void main(String[] args) { Holder<Applee> Applee = new Holder<Applee>(new Applee()); Applee d = Applee.get();// Applee.set(d); // Holder<Fruit> Fruit = Applee; // Cannot upcast Holder<? extends Fruit> fruit = Applee; // OK Fruit p = fruit.get(); d = (Applee)fruit.get(); // Returns ‘Object’ try { Orange c = (Orange)fruit.get(); // No warning } catch(Exception e) { System.out.println(e); } // fruit.set(new Applee()); // Cannot call set() // fruit.set(new Fruit()); // Cannot call set() System.out.println(fruit.equals(d)); // OK }} /* Output: (Sample)java.lang.ClassCastException: Applee cannot be cast to Orangetrue*///:
//: generics/SuperTypeWildcards.javaimport java.util.*;public class SuperTypeWildcards {static void writeTo(List<? super Apple> apples) {apples.add(new Apple());apples.add(new Jonathan());// apples.add(new Fruit()); // Error}} ///:~


java 萬用字元的使用-upcast

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.