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 element DataSet("Value1", null)
.
Now at some point I need to check if the entry with value "Value1"
has additionalValue
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 is null
.
How can I make it so that it doesn't throw an error and just skips the return
statement if additionalValue
is null
?
EDIT:
But the thing is that the element cannot be null
at the point where it checks additionalValue
as it passed through the element.getValue.equals("Value1")
condition.
for (DataSet element : dataSet) {
if (element.getValue.equals("Value1")) {
if (element.getAdditionalValue() != null) {
return element.getAdditionalValue();
}
}
}
Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .
keys method to check for an empty object. const empty = {}; Object. keys(empty). length === 0 && empty.
Using Object. Object. keys will return an Array, which contains the property names of the object. If the length of the array is 0 , then we know that the object is empty.
Using the typeof Operator Here we use the typeof operator with the null operator. The (! variable) means the value is not null and if it is checked with the typeof operator variable which has the data type of an object then the value is null.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With