What does equals(Object obj) do?

后端 未结 7 842
天涯浪人
天涯浪人 2020-12-02 21:23

I´ve often found an equals method in different places. What does it actually do? Is it important that we have to have this in every class?

   public boolean          


        
7条回答
  •  长情又很酷
    2020-12-02 22:01

    It redefines "equality" of objects.

    By default (defined in java.lang.Object), an object is equal to another object only if it is the same instance. But you can provide custom equality logic when you override it.

    For example, java.lang.String defines equality by comparing the internal character array. That's why:

    String a = new String("a"); //but don't use that in programs, use simply: = "a"
    String b = new String("a");
    System.out.println(a == b); // false
    System.out.println(a.equals(b)); // true
    

    Even though you may not need to test for equality like that, classes that you use do. For example implementations of List.contains(..) and List.indexOf(..) use .equals(..).

    Check the javadoc for the exact contract required by the equals(..) method.

    In many cases when overriding equals(..) you also have to override hashCode() (using the same fields). That's also specified in the javadoc.

提交回复
热议问题