I have a function in one of my classes that compares itself with another instance of the same class - and finds out which variables differ. This is for the purpose of minimizing network load with a main database (by only uploading data that needs to be uploaded, instead of uploading the whole object).
For this, I have been trying to make use of the object.equals()
function to compare the two objects.
I soon found that the object.equals()
does not handle null
s, and after reading this question, I understand why.
So an example of my broken code is as follows:
public class MyObject {
String myString;
String myString2;
public String getChangedVars(MyObject comparisonObj) {
ArrayList<String> changedVars = new ArrayList<String>();
if (!this.myString.equals(comparisonObj.myString))
changedVars.add("myString");
if (!this.myString2.equals(comparisonObj.myString2))
changedVars.add("myString2");
return changedVars.toString();
}
}
My question is - on the basis that either one of the variables being compared could be null, what is a simple way to compare two variables whilst avoiding a NullPointerException
?
Edit:
Simply checking for null on both objects first doesn't work well, as I still want to compare if the object has a reference or not. Eg, if one item is null
and the other is not, I want this to resolve to true
, as the variable has changed.