使用 Java 7 的 Objects.equals 来比较字段?

Mat*_*his 4 java performance

我只是生成了一些 equals 方法,想知道是否建议使用 Objects.equals() 方法将字段与 Java 7 进行比较。

Eclipse 会像这样生成 equals:

public class A
{
    private String a;
    private String b;

    @Override
    public boolean equals(Object obj)
    {
        if(this == obj)
            return true;
        if(obj == null)
            return false;
        if(getClass() != obj.getClass())
            return false;
        A other = (A)obj;
        if(a == null)
        {
            if(other.a != null)
                return false;
        }
        else if(!a.equals(other.a))
            return false;
        if(b == null)
        {
            if(other.b != null)
                return false;
        }
        else if(!b.equals(other.b))
            return false;
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道,这是否是一个好习惯:

public class A
{
    private String a;
    private String b;

    @Override
    public boolean equals(Object obj)
    {
        if(this == obj)
            return true;
        if(obj == null)
            return false;
        if(getClass() != obj.getClass())
            return false;
        A other = (A)obj;
        return Objects.equals(a, other.a) && Objects.equals(b, other.b);
    }
}
Run Code Online (Sandbox Code Playgroud)

你怎么认为?我试图测试它的性能,但它没有显示出任何区别..

Tag*_*eev 5

是的,这是一个很好的做法。这样,该equals方法看起来更清晰,除了附加方法调用之外没有任何缺点,在大多数情况下,JIT 编译器可以轻松内联这些方法。请注意,它Objects.equals首先出现在 Java 7 中,而不是 Java 8。