7

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();
        }
     }
}
0xCursor
  • 2,242
  • 4
  • 15
  • 33
SharkyLV
  • 319
  • 2
  • 4
  • 12

2 Answers2

21

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();
}
davioooh
  • 23,742
  • 39
  • 159
  • 250
3

This will sort you out:

if (element != null && element.getAdditionalValue() != null) {
    return element.getAdditionalValue();
}
duffymo
  • 305,152
  • 44
  • 369
  • 561