[英]Java Generics problems
I have this class Entry... 我有这堂课...
public class Entry <K, V> {
private final K mKey;
private final V mValue;
public Entry() {
mKey = null;
mValue = null;
}
}
What happens if I use an int as the mKey? 如果将int用作mKey会怎样? As far as I know ints can't be null!
据我所知,int不能为null!
A variable of type Integer
can be null. 类型为
Integer
的变量可以为null。 An int
cannot be null. 一个
int
不能为null。 The latter is the primitive type, the former is a wrapper reference type for dealing with primitives as an Object. 后者是基元类型,前者是将基元作为对象处理的包装器引用类型。 If you're using this:
如果您使用的是:
Entry<Integer, String> myEntry;
Then you are necessarily using the wrapper type. 然后,您必须使用包装器类型。 Primitives can't be used as type parameters in Java so you can't have
Entry<int, String>
for example (it won't compile). 在Java中,基元不能用作类型参数,因此您不能使用
Entry<int, String>
(它将不会编译)。
您不能将基元用作类型参数。
Generic type parameters need to be objects, they can't be primitives. 泛型类型参数必须是对象,而不能是基元。 So you can use the
Integer
wrapper class around mKey / mValue and set it to null, but trying to use the int primitive will always give you a compilation error. 因此,您可以在mKey / mValue周围使用
Integer
包装器类并将其设置为null,但是尝试使用int原语将始终给您带来编译错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.