Check if element in object is null
Solution 1
I think the problem is that your element
object is null
, so you have to check it before checking additionalValue
.
if (element != null && element.getAdditionalValue() != null){
return element.getAdditionalValue();
}
Solution 2
This will sort you out:
if (element != null && element.getAdditionalValue() != null) {
return element.getAdditionalValue();
}
SharkyLV
Updated on September 03, 2020Comments
-
SharkyLV over 3 years
I have a simple dataset class similar to:
class DataSet { private String value; private String additionalValue; public DataSet(String value, String additionalValue) { this.value = value; this.additionalValue = additionalValue; } public String getAdditionalValue() { return this.additionalValue; } }
Then I have created an
ArrayList<DataSet>
and added a new elementDataSet("Value1", null)
.Now at some point I need to check if the entry with value
"Value1"
hasadditionalValue
and if it does, what it is.I do a simple loop checking if
value.equals("Value1") == true
, then I do:if (element.getAdditionalValue() != null) { return element.getAdditionalValue(); }
However, as soon as it gets to the
if
statement, it throws an error saying that the value isnull
. How can I make it so that it doesn't throw an error and just skips thereturn
statement ifadditionalValue
isnull
?EDIT:
But the thing is that the element cannot be
null
at the point where it checksadditionalValue
as it passed through theelement.getValue.equals("Value1")
condition.for (DataSet element : dataSet) { if (element.getValue.equals("Value1")) { if (element.getAdditionalValue() != null) { return element.getAdditionalValue(); } } }