Why is implicit conversion from int to Long not possible?

后端 未结 3 396
攒了一身酷
攒了一身酷 2021-01-05 02:14

I can implicitly conver int to long and long to Long. Why is it not possible to implicitly convert int to Long? Why can\'t Java do the implicit conversion on the last line o

相关标签:
3条回答
  • 2021-01-05 02:22

    Boxing only works with primitives. That's why.

    Try this: Long.valueOf(int);

    Documentation

    0 讨论(0)
  • 2021-01-05 02:30

    Long and Integer are objects. Boxing/unboxing only works with primitives. Doing Long boxedLong = i is like Long boxedLong = new Integer(10), that's a no no ! Plus, remember that there is no inheritance between Long and Integer so even Integer i = new Long() is not valid

    0 讨论(0)
  • 2021-01-05 02:42

    the biggest difference I see between long and Long in this context is that Long may be null. If there's a possibility you might have missing values the Long object will be helpful as the null can indicate missing values. If you're using primitives you'll have to use some special value to indicate missing, which is probably going to be a mess. Speed or size is not likely to be an issue unless you're planning on making an array of a million of these things and then serializing. (When to use Long vs long in java?)

    In truth, there is no practical reason. Except that int is a primitive, long is a primitive, but Long is not.

    I suggest you use Long.valueOf()

    So like this:

    Long longValue = Long.valueOf(InsertIntHere);
    
    0 讨论(0)
提交回复
热议问题