简体   繁体   中英

Can I avoid a null check when comparing an Integer that may be null with a constant?

I am using the Struts2 framework in Java 7, combined with Dojo 1.8 or 1.9 (1.3 in rare cases) as a frontend library depending on the page. I have several search pages with Dojo Selects or FilteringSelects that return an Integer value: 0 and higher are legitimate values, -1 and null are values that are returned when nothing is selected in the Select, depending on whether the page has just been loaded or whether it has been reset by Javascript.

When searching, I have to check whether there's a legitimate value in the Integer, and if not set it to null so my search service method knows that it should ignore that. This means setting it to null if it's -1, or just leaving it as is if it's either null or >= 0.

I currently do this via the following check at the start of the method:

// as a class constant
public static final int DOJO_NO_SELECTION = -1;

// in my search action
if (view.getNullableInteger() != null && view.getNullableInteger() == DOJO_NO_SELECTION) {
    view.getNullableInteger(null);
}

I feel like that extra nullcheck in front is ugly and would like to avoid it. I've tried doing it like this:

// as a class constant
public static final Integer DOJO_NO_SELECTION = new Integer(-1);

if (view.getNullableInteger().equals(DOJO_NO_SELECTION)) {
    view.getNullableInteger(null);
}

I've tried flipping the 2 around:

if (DOJO_NO_SELECTION.equals(view.getNullableInteger())) {
    view.getNullableInteger(null);
}

but both of these give me a NullPointerException when view.getNullableInteger() is null.

Is it possible to write this code so the nullcheck is avoided, but it still works for nulls?

Use Objects.equals :

if (Objects.equals(view.getNullableInteger(), DOJO_NO_SELECTION)) {
    view.getNullableInteger(null);
}

Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned . Otherwise, equality is determined by using the equals method of the first argument.

Use a Yoda condition , and explicitly box the constant int to an Integer :

if (Integer.valueOf(DOJO_NO_SELECTION).equals(view.getNullableInteger()) {
  // ...
}

Note that Integer.valueOf(-1) is guaranteed to be cached , so this does not create a new object on each call.

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