[英]java array assignment question
當使用方法Arrays.deepToString(Object [] a)時,我遇到了這個問題,可以用這種方式解決。
Object [] not_allowed = new int[]{7, 9, 8};
Object [] allowed = new int[][]{{1, 2, 3}, {6, 5, 4}};
為什么在單維情況下不允許將int []分配給Object [],但在多維情況下卻允許這樣做。
像int
這樣的基本類型不是對象,而數組是對象-您可以將任何數組分配給對象引用
Object o = new int[]{7, 9, 8};
new int[][]
是對象的數組,因此可以分配給Object[]
。 您可能想要編寫這樣的實用程序方法來執行所需的操作:
public static String arrayToString(Object o) {
if(o instanceof Object[]) {
return Arrays.deepToString((Object[]) o);
}
else if(o instanceof long[]) {
return Arrays.toString((long[]) o);
}
else if(o instanceof int[]) {
return Arrays.toString((int[]) o);
}
else if(o instanceof short[]) {
return Arrays.toString((short[]) o);
}
else if(o instanceof byte[]) {
return Arrays.toString((byte[]) o);
}
else if(o instanceof float[]) {
return Arrays.toString((float[]) o);
}
else if(o instanceof double[]) {
return Arrays.toString((double[]) o);
}
else if(o instanceof boolean[]) {
return Arrays.toString((boolean[]) o);
}
throw new IllegalArgumentException("input is not an array");
}
例:
Object intArray = new int[]{7, 9, 8};
Object[] intintArray = new int[][]{{1, 2, 3}, {6, 5, 4}};
Object[] intintintArray = new int[][][]{{{1, 2, 3}, {6, 5, 4}},
{{1, 2, 3}, {6, 5, 4}}};
System.out.println(arrayToString(intArray));
System.out.println(arrayToString(intintArray));
System.out.println(arrayToString(intintintArray));
輸出:
[7, 9, 8]
[[1, 2, 3], [6, 5, 4]]
[[[1, 2, 3], [6, 5, 4]], [[1, 2, 3], [6, 5, 4]]]
int
不是Object
,這就是第一次分配不合法的原因: int
的數組不是Object
的數組。
但是數組,無論如何, 都是對象。 您已成功將外部數據結構(即數組的數組)分配給Object
的數組。
小寫的int是基元,不繼承自Object。 嘗試改用Integer。
第一次分配不起作用,因為int []的元素類型是int,而不是Object。 由於(您正在嘗試分配給Object [],所以元素類型應該是Object,而不是int)
第二個分配確實起作用,因為int []是一個對象,因此int [] []是一個Object []。
您的第一行無效:
Object [] not_allowed = new int[]{7, 9, 8};
這是因為int
不是Object
。 這將是有效的:
Object allowed = new int[]{7, 9, 8};
值得一提的是,允許的行
Object [] allowed = new int[][]{{1, 2, 3}, {6, 5, 4}};
實際上也不應該是因為您應該能夠跟進
allowed[0] = "Surprise!";
因此設法將String
放入僅包含int[]
的數組中。 因此,Java必須在運行時檢查對數組元素的每個分配,以確保所分配的元素與數組的實際類型兼容,而不僅僅是讓編譯時類型檢查來處理它。 因此,上面的代碼可以編譯,但是在嘗試分配String
將導致異常。
此問題也只影響數組。 當將泛型添加到Java時,設計人員會更好地理解,並且在泛型集合中, int[]
的集合不是Object
集合的子類型,因此,如果在您的示例中,從數組切換為泛型ArrayList
,例如,這兩行都不會編譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.