Check for an item in the object

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 created an ArrayList<DataSet> and added a new element new DataSet("Value1", null)

Now at some point I need to check if the value with Value1 has an extraValue value, and if so, what is it.

I do a simple check loop if value.equals("Value1") == true , then I do

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

However, as soon as he receives the if statement, he throws an error saying that the value is null. How can I make it not throw an error and just skip the return if the extra shaft is null?

EDIT:

But the fact is that the element cannot be null at the point where it checks the additional value when it passes through the element.getValue.equals ("Value1") condition.

 for (DataSet element : dataSet) { if (element.getValue.equals("Value1")) { if (element.getAdditionalValue() != null){ return element.getAdditionalValue(); } } } 
+4
source share
2 answers

I think the problem is that your element object is null , so you need to check it before checking additionalValue .

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

This will help you figure out:

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

All Articles