java diamond 有什么用_Diamond语法何时在Java 8中不起作用?
從Java 7開始,菱形語法并不總是在方法參數中起作用,例如 為什么Diamond運算符不適用于Java 7中的java.util.Collections方法? 。 該問題的答案提到Java 8中的目標類型推斷可解決該問題。
是否還有其他情況無法使用菱形語法?
不是專門針對菱形運算符,而是針對lambda返回類型的Java 8s類型推斷的弱點:stackoverflow.com/q/26379408/502399
diamond運算符不能總是在Java 8中使用。最初的改善Java 8推理的計劃(JEP 101)有兩個目標:
在方法上下文中添加對方法類型參數推斷的支持
添加對鏈式調用中方法類型參數推斷的支持
僅第一個實施。從JEP借用該示例,請考慮以下類:
class List {
static List cons(Z head, List tail) { ... };
E head() { ... }
}
在Java 8中,改進的方法上下文推論允許以下內容進行編譯。使用Java 7,它將失敗并顯示錯誤expected List, found List
List l = List.cons(42, new List<>());
但是,需要推理鏈式調用的示例仍不適用于Java 8:
Integer i = new List<>().head();
JSR 335的D部分包含有關為何Java 8放棄了鏈式表達式推理的提示:
There has been some interest in allowing inference to"chain": in a().b(), passing type information from the invocation of b to the invocation of a. This adds another dimension to the complexity of the inference algorithm, as partial information has to pass in both directions; it only works when the erasure of the return type of a() is fixed for all instantiations (e.g. List). This feature would not fit very well into the poly expression model, since the target type cannot be easily derived; but perhaps with additional enhancements it could be added in the future.
還有一些其他無法使用鉆石的示例。
如果算錯了,那么jdk8u25之前的javac不會編譯它。 (請參閱JDK-8029002)
class Test {
class C> {}
void m() {
C< ? > i = new C<>();
}
}
error: incompatible types: cannot infer type arguments for Test.C<>
C< ? > i = new C<>();
^
reason: inferred type does not conform to upper bound(s)
inferred: Test.C
upper bound(s): Test.C>,Test.C
where CAP#1 is a fresh type-variable:
CAP#1 extends Test.C from capture of ?
新類型推斷實現還存在一個性能問題(JDK-8051946),該問題可能會影響使用菱形運算符的代碼。如果使用菱形運算符,下面的示例將花費幾分鐘的時間進行編譯。
class Test {
< T > T and(T a, T b) { return null; }
class C< T > {}
void g(String s) {}
void g(Object s) {}
void m() {
g(
and(
and(
and(
and(
and(
and(
and(new C<>(),
new C<>()),
new C<>()),
new C<>()),
new C<>()),
new C<>()),
new C<>()),
new C<>()));
}
}
加一; 這樣的答案會讓您超越Jon Skeet。
好的解釋+1
總結
以上是生活随笔為你收集整理的java diamond 有什么用_Diamond语法何时在Java 8中不起作用?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js之 foreach, map, ev
- 下一篇: eclipse tomcat新建一个_J