根據 Maurice Naftalin 的 Java Generic 和 Collections,在以下選項中 -
- 物件實體串列
- obj 實體串列<?>
- obj 實體串列<? 擴展物件>
第 1 和第 2 是允許的,但第 3 不是在 java 8(版本“1.8.0_321”)中作業正常。選項 1 和 2 編譯,選項 3 給出編譯錯誤。但是第三個選項適用于 java 17(版本“17.0.1”2021-10-19 LTS)。你能幫我理解為什么它在java 17中作業。我正在嘗試的示例代碼 -
var a = List.of(2,3,4,5,23);
var b = a instanceof List<? extends Object>;
return b;
uj5u.com熱心網友回復:
在 Java 16 之前, 的唯一目的instanceof是檢查被參考的物件是否可以分配給指定的型別,并且由于型別擦除阻止檢查物件是否真的可以分配給引數化型別,所以允許運算式假裝是沒有意義的這樣的測驗是可能的。
唯一可以測驗的是物件是否是的實體,List因此,它只允許寫… instanceof Listor … instanceof List<?>,因為兩者都沒有假裝測驗串列的元素型別。
從 Java 16(自 14 開始提供預覽版)開始,instanceof允許宣告指定型別的新變數。
例如:
public void someMethod(Iterable<String> i) {
if(i instanceof List<String> l) {
if(l.isEmpty()) return;
// optimized List processing
} else {
// generic iterable processing
}
}
這相當于
public void someMethod(Iterable<String> i) {
if(i instanceof List<String>) {
List<String> l = (List<String>)i;
if(l.isEmpty()) return;
// optimized List processing
} else {
// generic iterable processing
}
}
對于新變數的宣告,僅限于原始型別或通配符型別是不切實際的。因此,現在允許指定與隱含變數宣告和賦值相關的實際型別引數。由于仍然無法檢查元素型別,因此您只能指定編譯時源型別可以在沒有未經檢查的強制轉換的情況下強制轉換為的型別。
因此,以下內容無效
Iterable<?> i = null;
boolean b = i instanceof List<String>;
因為你不能安全地從Iterable<?>to 轉換List<String>。
在您的示例中,var a = List.of(2,3,4,5,23);宣告a為List<Integer>,因此a instanceof List<? extends Object>是有效的,因為List<Integer>可以分配給List<? extends Object>(即使沒有強制轉換)。
Of course, specifying element types which are not checked is only useful if you declare a variable like in the first example. But the Java language follows the principle of not adding extra rules just because some construct is less useful than the other. Therefore, you can now always specify actual type arguments to instanceof following the same rules, whether you declare a variable or not.
This feature is called Pattern Matching as it is considered a special case of a broader concept which Java is heading for. In JDK 17, there’s a similar feature for switch available as preview.
See also §14.30. Patterns in the Java Language Specification.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/426118.html
下一篇:如何在C#中正確轉換貨幣
