我正在使用Oracle JDK 7u79。我不知道为什么下面的代码会产生编译错误:
package generics;
import java.util.Collection;
import java.util.Collections;
class SomeClass {
public Collection<String> getStringCollection() {
return Collections.singleton("hello");
}
}
class SomeTypedClass<T> {
public Collection<String> getStringCollection() {
return Collections.singleton("hello");
}
}
public class SomeTest {
public static void main(String[] args) {
final int length1 = new SomeClass() .getStringCollection().iterator().next().length();
final int length2 = new SomeTypedClass().getStringCollection().iterator().next().length(); // compilation error
}
}
错误:
Error:(21, 89) java: cannot find symbol
symbol: method length()
location: class java.lang.Object
我指定常量泛型类型Collection<String>
作为方法的参数getStringCollection()
,所以我认为无论是SomeClass
和SomeTypedClass
应该没有错误编译。
为什么会这样?在Collection
不强制转换的情况下不断输入正确的解决方案是什么?
实际上,由于您SomeTypedClass<T>
希望T
传入一个类型,即使它没有使用该类型,您也需要在以下代码中执行此操作SomeTest
:
public class SomeTest {
public static void main(String[] args) {
final int length1 = new SomeClass() .getStringCollection().iterator().next().length();
final int length2 = new SomeTypedClass<String>().getStringCollection().iterator().next().length(); // no more compilation error
}
}
我使用了String
,但是您可以使用Object
,因为T
实际上并没有使用。
可能值得考虑对您的SomeTypedClass
班级做更多这样的事情,具体取决于您的实际情况:
class SomeTypedClass<T> {
public Collection<T> getTypedCollection(T object) {
return Collections.singleton(object);
}
}
然后,您可以执行以下操作:
final int length2 = new SomeTypedClass<String>().getTypedCollection("hello").iterator().next().length();
如果您仅对衍生自的类感兴趣String
,还可以执行以下操作:
class SomeTypedClass<T extends String> {
public Collection<T> getStringCollection(T object) {
return Collections.singleton(object);
}
}
然后,您可以执行以下操作:
final int length2 = new SomeTypedClass<String>().getStringCollection("hello").iterator().next().length();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句