开发者

convert small long to big Long in java

开发者 https://www.devze.com 2023-01-14 22:28 出处:网络
long myvariable; can\'t have value null but Long myBigVariable; can, so I want to convert/cast myvariable to big Long so I can assign it value开发者_如何转开发 of null. How can I do that?

long myvariable; can't have value null but Long myBigVariable; can, so I want to convert/cast myvariable to big Long so I can assign it value开发者_如何转开发 of null. How can I do that?

I tried myvariable = new Long(null); and myvariable = (Long)(null); they both failed, is there another solution to this ?

I can't change myvariable to type Long, it has to stay long.


In order to create a null Long:

Long myvariable = null;

EDIT: I can't change myvariable to type Long, it has to stay long.

Then no, you cannot set a primitive to null.


The primitive type long has a default value of 0 (0L to be precise) even if you don't assign it anything if it is a field. If it is a local variable you should initialize it explicitly. So you can't have a null value for it.

If you want to have some value that is considered "invalid" or "non-existent", but you don't want it to be 0, you can use:

  • -1
  • Long.MAX_VALUE / Long.MIN_VALUE (or Integer.MAX_VALUE)

And then have:

Long myBigVariable = myvariable == Long.MAX_VALUE 
       ? null 
       : myvariable; // autoboxing here; altarnatively new Long(myvariable)


long is a primitive 64 bit integer. Every combination of 64 bits is used to represent a value. There is no way to represent null using long.

Long is a class that represents a 64 bit integer. You can create a Long instance to represent any of the values that long can; or use a null instance to represent null.

Long myLongValue = 9223372036854775807L; // OK
Long myLongNull = null; // OK
long myvariable = null; // Error


No, you can't do that. The long value must be valuated.

Each object (including Long) can be null, but no primitive type (int, long, etc.) can. For that reason, a null Long object can't be cast to its primitive type.

When a Long object is cast into a long, the "longValue()" method is called to perform the cast. This method can't be called on a null object: it would result in a nullPointerException.


I can't change myvariable to type Long, it has to stay long.

Then you can't assign null to that variable. There is no way of assigning null to a primitive variable.


I tried myvariable = new Long(null);

Well.. this works for me! :)


myvariable = new Long(null); can be complied , but in running time ,it will throws NumberFormatException


Depends which version of Java you are using. Autoboxing is supported since Java 1.5 (or 1.4). This means, that a variable of type long will be automatically converted to Long if this needs to be done.

0

精彩评论

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