简体   繁体   中英

Convert a nullable integer value in Java (Short, Long etc.)

Is there any standard way of converting between non-primitive integer types in Java that properly retains null values? Something like:

// Pseudocode
Short shortVal = null;
Long longVal = Numbers.toLong(shortVal); // longVal is expected to be null here

Obviously I cannot use shortVal.longValue() here as a NullPointerException will be thrown.

Plain simple "casting" and the "ternary conditional operator" would be the minimal and fastest solution.

Short shortVal = null;
Long longVal = shortVal == null ? null : (long) shortVal;

Since you don't seem to know about casting, here's an example that does not work - and how to fix it. Mind that the problem of null is completely ignored here - this is just a quirky aspect of casting that you might want to know, that's all.

Double doubleVal = 1d;
Float floatVal = (float) doubleVal; // Inconvertible types!

Working version:

Double doubleVal = 1d;
Float floatVal = (float) (double) doubleVal;

What about using the Java 8 API Optional:

Short shortVal = null;
Optional<Long> longVal = Optional.ofNullable(shortVal != null ? new Long(shortVal) : null);
System.out.println(longVal.isPresent());

The output for this code snippet is false , which indicates that the value is null.

怎么样:

Long longVal = shortVal != null ? Numbers.toLong(shortVal) : null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM