8

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();
        }
     }
}
7
  • 10
    if ( element != null && element.getAdditionalValue() != null) { your code here} ... Commented Jul 13, 2012 at 12:59
  • Can you post the rest of the code? Commented Jul 13, 2012 at 12:59
  • 1
    if(value.equals("Value1") == true) can be written as if(value.equals("Value1")) Commented Jul 13, 2012 at 13:00
  • 3
    If value is null, calling .equals on it will throw. Instead call .equals on the string and check against value. Commented Jul 13, 2012 at 13:00
  • stackoverflow.com/q/271526/106261 Commented Jul 13, 2012 at 13:00

2 Answers 2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

3

This will sort you out:

if (element != null && element.getAdditionalValue() != null) {
    return element.getAdditionalValue();
}

2 Comments

If element == null can element.anythingElse() be anything but null?
@Mob no, and thats why shortcircuit compare is used

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.