Comparing two objects, either of which could be null

后端 未结 4 1560
攒了一身酷
攒了一身酷 2021-01-04 19:06

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 minimi

相关标签:
4条回答
  • 2021-01-04 19:47

    You can use Apache object utils

    ObjectUtils.equals(Object object1, Object object2) -- Returns boolean

    this method has been replaced by java.util.Objects.equals(Object, Object) in Java 7

    0 讨论(0)
  • 2021-01-04 19:47

    Use StringUtils provided by apache

    StringUtils.equals(myString,comparisonObj.myString);
    
    0 讨论(0)
  • 2021-01-04 19:56

    There is new utility class available in jdk since 1.7 that is Objects .

    This class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.

    You can use Objects.equals, it handles null.

    Objects.equals(Object a, Object b) Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.

    if(Objects.equals(myString,myString2)){...}
    
    0 讨论(0)
  • 2021-01-04 20:04
        if (this.myString != null && this.myString.equals(comparisonObj.myString))
    {
                    changedVars.add("myString");
    }
    
    0 讨论(0)
提交回复
热议问题