private boolean checkStatusAct(Contract contract) {
if (contract.getActs() == null || contract.getActs().isEmpty()) {
return true;
} else if (contract.getActs() != null || (!contract.getActs().isEmpty())) { //here
for (ContractAct contractAct : contract.getActs()) {
if (contractAct.getStatusId() == 15) {
return true;
}
}
}
return false;
}
Isn't it successively checked one by one and if it's not null (!= null || .isEmpty()) it never produces a NullPoi
CodePudding user response:
In Jav 8 or higher version. Assuming contract.getActs()
is a list. You don't need to write else: You can do like
private boolean checkStatusAct(Contract contract) {
if (contract.getActs() == null || contract.getActs().isEmpty()) {
return true;
}
return contract.getActs().stream().anyMatch(c -> c.getStatusId() == 15);
}
CodePudding user response:
The problem is that
contract.getActs() != null || (!contract.getActs().isEmpty())
will throw a NullPointerException if contract.getActs()
returns null. In that case contract.getActs() != null
is false and because of the ||
operator the JVM must evaluate contract.getActs().isEmpty()
which will throw the NullPointerException.
To correct this you should write
contract.getActs() != null && (!contract.getActs().isEmpty())
But this is effectively not needed, because your first if
condition already handles the cases where contract.getActs()
or contract.getActs().isEmpty()
. It would be better to rewrite your code as
private boolean checkStatusAct(Contract contract) {
if (contract.getActs() == null || contract.getActs().isEmpty()) {
return true;
} else {
for (ContractAct contractAct : contract.getActs()) {
if (contractAct.getStatusId() == 15) {
return true;
}
}
}
return false;
}
Starting from Java 8 you can also use streams (navnath's solution).