开发者

Java Generics problems

I have this class Entry...

public class Entr开发者_如何学运维y <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? As far as I know ints can't be null!


A variable of type Integer can be null. An int cannot be 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).


You can't use primitives as type parameters.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜