Check if element in object is null

56,328

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();
}
Share:
56,328
SharkyLV
Author by

SharkyLV

Updated on September 03, 2020

Comments

  • SharkyLV
    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 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();
            }
         }
    }