Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element in object is null

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();
        }
     }
}
like image 853
SharkyLV Avatar asked Jul 13 '12 12:07

SharkyLV


People also ask

How do you check if an object has null value?

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 .

How do you check if an object has a blank key value?

keys method to check for an empty object. const empty = {}; Object. keys(empty). length === 0 && empty.

How do you check if an object is 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.

How do you check if the object contains null in JavaScript?

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.


1 Answers

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();
}
like image 63
davioooh Avatar answered Sep 23 '22 15:09

davioooh