我想明白下面的代碼片段,搜索與問候計算器鏈接lowerbound和upperbound下界通配符
只是想獲得在以下行的混亂,
SI = S //確定爲什麼?對象數組可以隱含地轉換爲整數數組?
List<? extends Number> l = new ArrayList<>();
List<? extends Integer> i = new ArrayList<>();
l = i;//OK i is a subtype of l
List<? super Number> s = new ArrayList<>();
List<? super Integer> si = new ArrayList<>();
si = new ArrayList<Integer>();//OK understand integer matches the pattern of ? super Integer
s = new ArrayList<Object>();//OK understand that object is superclass of Number
si=s//OK why? arrays of objects can be implicitly casted to arrays of integers?
//consider this
List<Integer> integers = new ArrayList<Integer>();
List<Object> objects = new ArrayList<Object>();
integers = objects; //NOT OK Type mismatch: cannot convert from List<Object> to List<Integer>
//consider this
Integer ten = 10; //integer ten
Object none = new Object();//some none
ten = none;//NOT OK none cannot be implicitly casted to ten
任何幫助表示讚賞
只是爲了讓編譯器正確解析wrt泛型,如果我說{si超級整數} = {s數組超級數組}編譯器不關心右側(超級數字)類型參數是否可以投射到左側(整數超級)....它只關心左類型參數是右類型參數的後代/子類型還是隻關心右類型參數是左類型參數的超類型/祖先? – chebus
編譯器不在乎,但Number的任何超級都是Integer的超級,因爲Number是Integer的超級。另外要注意將數組與數組等同爲數組列表是有趣的對象,它們是基本類型和類別的類別,並且整數數組可以被分配給數組數組,但是整數列表不能被分配給數字列表,因爲通用系統不允許它.. – redge
我明白,Number是整數的超類。假設這種情況, 列表 super A> lst = new ArrayList <>(); lst.add({A或A的子類的實例,它可以是A1,A2等任何東西。 假設我已經添加了s.add(A2); 現在, 列表 super A1> sl = new ArrayList <>(); sl.add({A1的實例或A1的子類)}) 假設我添加了sl.add(A1); 假定lst = sl; //這意味着我只能添加A1或A1的子類,所有這些子類都繼承A。 因此,我們說A1的子類列表(從A繼承)可以安全地分配給A的子列表? – chebus