不兼容的类型 Void 和 Object – Java 泛型

huangapple 未分类评论44阅读模式
英文:

Incompatible types Void and Object - Java Generics

问题

以下代码会抛出异常:

"Incompatible types. Required Sample<Void> but create was inferred to Sample<T>. Incompatible equality constraints: Void and Object".
public class SampleClass{
  public static <T> Sample<T> create(String str) {}
}

Sample<Void> sample = SampleClass.create("abc");
英文:

Below code throws

&quot;Incompatible types. Required Sample&lt;Void&gt; but create was inferred to Sample&lt;T&gt;. Incompatible equality constraints:Void and Object&quot;. 

public class SampleClass{
  public static &lt;T&gt; Sample&lt;T&gt; create(String str) {}
}

Sample&lt;Void&gt; sample = SampleClass.create(&quot;abc&quot;);

答案1

得分: 0

它实际上确实有效。

完整示例:

public class SampleClass {

	public static void main(String[] args) {
		Sample<Void> sample = SampleClass.create("abc");

	}

	public static <T> Sample<T> create(String str) {
		return null;
	}

	private static class Sample<T> {
	}
}

(在JDK 11下)编译并且可以正常执行。

英文:

It actually does work.

Full example:

public class SampleClass {

	public static void main(String[] args) {
		Sample&lt;Void&gt; sample = SampleClass.create(&quot;abc&quot;);

	}

	public static &lt;T&gt; Sample&lt;T&gt; create(String str) {
		return null;
	}

	private static class Sample&lt;T&gt; {
	}
}

Compiles and executes just fine (with JDK 11).

huangapple
  • 本文由 发表于 2020年4月6日 23:59:19
  • 转载请务必保留本文链接:https://java.coder-hub.com/61063884.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定