== 运算符和 equals() 有什么区别? (使用 hashcode() ???)

发布于 2024-10-09 03:48:19 字数 1885 浏览 9 评论 0原文

我正在更深入地学习哈希码并发现:

1。如果您重写 equals(),则也必须重写 hashcode()。

2.要查找 2 个对象是否是同一对象,请使用 == 运算符

考虑到这两个因素,在 Java 中,我假设当使用 == 运算符 来比较如果 2 个实例是相同或不同,

if(object1 == object2)

实际上正在做

if(object1.hashcode() == object2.hashcode())

但看来我通过运行下面的测试是错误的。

public class Main {

    public static void main(String[] args){
        Obj1 one = new Obj1();
        Obj1 two = new Obj1();
        //is this calling hashCode() in backend???
        if(one == two) {
            System.out.println("same");
        }
        else {
            System.out.println("nope");
        }
        //this is of course return true
        if(one == one) {
            System.out.println("one and one is same");
        }
    }
}

class Obj1 {
    @Override
    public int hashCode() {
        System.out.println("hashCode() is called");
        return 111;
    }
    @Override
    public boolean equals(Object another) {
        System.out.println("equals() is called");
        return false;
    }
}

根据使用 == 运算符 的测试,看看是否调用了 equals() ,而没有调用。

所以我的问题是 == 运算符 是否可以用来比较对象是否相同,重写 equals()hashCode( ) 比较方法? == operator 不是已经完成了这项工作吗?

参考:

重写 hashCode() - 这足够好吗?

http://mindprod.com/jgloss/hashcode.html

http://download.oracle.com/javase/ 1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)

I was learning hashcode in more depth and figured that:

1. If you override equals(), you must override hashcode() too.

2. To find if 2 objects are same object, use == operator

Given those 2 factors, in Java I was assuming that when == operator is used to compare if 2 instances are same or not,

if(object1 == object2)

is actually doing

if(object1.hashcode() == object2.hashcode())

But it appears I was wrong by running the test below.

public class Main {

    public static void main(String[] args){
        Obj1 one = new Obj1();
        Obj1 two = new Obj1();
        //is this calling hashCode() in backend???
        if(one == two) {
            System.out.println("same");
        }
        else {
            System.out.println("nope");
        }
        //this is of course return true
        if(one == one) {
            System.out.println("one and one is same");
        }
    }
}

class Obj1 {
    @Override
    public int hashCode() {
        System.out.println("hashCode() is called");
        return 111;
    }
    @Override
    public boolean equals(Object another) {
        System.out.println("equals() is called");
        return false;
    }
}

According to the test which uses == operator and see if equals() is called and it wasn't.

So my question is if == operator can used to compare if the object is same or not, what is the point of overriding equals() and hashCode() method for comparison? Isn't == operator do the job already?

reference:

Overriding hashCode() - is this good enough?

http://mindprod.com/jgloss/hashcode.html

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

酒几许 2024-10-16 03:48:19

== 运算符确定 2 个引用是否指向同一个对象。

因此,

 Object o1 = new Object();
 Object o2 = o1;

 o1 == o2; //true

 o2 = new Object();

 o1 == o2 // false

Object.equals() 方法是“如何确定两个对不同对象的对象的引用是否相等?”

如果两个引用指向同一个对象,则两者都

o1 == o2 
o1.equals(o2) 

应该为 true。

但如果 o1 和 o2 不是同一个对象,它们在逻辑上仍然可能相等。对于任何给定的类,equals 取决于对象背后的语义。例如,考虑一个类,其中 field1 和 field2 由用户设置,但 field3 是计算出来的,并且其计算具有随机元素。在这种情况下,将 equals 定义为仅依赖于 field1 和 field2,而不依赖于 field3 可能是有意义的。这就是为什么 equal 是必要的。

the == operator determines if 2 references point to the same object.

So

 Object o1 = new Object();
 Object o2 = o1;

 o1 == o2; //true

 o2 = new Object();

 o1 == o2 // false

the Object.equals() method is "how do I determine if 2 references to objects, that are not the same object, are equal?"

If two references point to the same object, both

o1 == o2 
o1.equals(o2) 

should be true.

But if o1 and o2 are not the same object, they still might be equal logically. For any given class, equals depends on the semantics behind the object. For example, consider a class where field1 and field2 are set by the user, but field3 is computed and has a random element to its computation. It might make sense to define equals in this case to only depend on field1 and field2, and not field3. Thats why equals is necessary.

兮子 2024-10-16 03:48:19

== 是身份。

.equals() 是相等。

.equals() 默认仅使用 == (就像 hashCode() 默认为 System.identityHashCode() > 但如果有更有意义的方法来检查相等性,您可以覆盖它们。通常,这是一种“结构”相等性,即:是 this .equal( 的所有部分。 )that 的所有部分?

== is identity.

.equals() is equality.

.equals() defaults to just using == (just like hashCode() defaults to System.identityHashCode() but you can override them if there's a more meaningful way to check for equality. Typically this is a sort of "structural" equality. ie: are all of the pieces of this .equal() to all of the pieces of that?

白芷 2024-10-16 03:48:19

大多数问题已经得到解答,所以这是另一个有启发性的例子:

String s1 = "foo";
String s2 = "foo";
System.out.println(s1 == s2); // true, because same reference (string pool)

String s3 = new String("foo");
String s4 = new String("foo");
System.out.println(s3 == s4); // false, because different reference
System.out.println(s3.equals(s4)); // true, because same value

Most is already answered, so here's just another enlightening example:

String s1 = "foo";
String s2 = "foo";
System.out.println(s1 == s2); // true, because same reference (string pool)

String s3 = new String("foo");
String s4 = new String("foo");
System.out.println(s3 == s4); // false, because different reference
System.out.println(s3.equals(s4)); // true, because same value
紅太極 2024-10-16 03:48:19

如果您还没有副本;购买 Joshua Bloch 所著的《Effective Java》。

这是 Java 开发人员事实上的参考资料,包含有关此(以及许多其他)主题的大量信息。

If you don't already have a copy; buy a copy of Effective Java by Joshua Bloch.

This is the de facto reference for Java developers and has a lot of information on this (and many other) subject.

反差帅 2024-10-16 03:48:19

== (用于对象而不是原始值)测试两个对象是否实际上是同一个对象;它比较指针是否实际上指向同一内存位置。

.equals() 由对象本身定义。

String s1 = new String("Hello");
String s2 = new String("Hello");

boolean b1 = ( s1 == s2 ) ; // false: s1 and s2 point to different objects
boolean b2 = ( s1.equals(s2) ) ; // true: s1 and s2 both represent the same
                                 //       piece of text - "Hello"

.hashCode() 是一个优化技巧(无论如何,在它的大多数用途中)。标准库中的很多代码都假设如果o1.equals(o2)==trueo1.hashCode()==o2.hashCode () 并且如果 o1.hashCode()!=o2.hashCode() then o1.equals(o2)==false 为了更快地工作。

这种优化最明显的例子是 HashMap 类。这使得使用键真正快速检索对象,但如果 hashCode 和 equals 对于键元素不能正常工作,则会严重中断。事实上,这是 String 类不可变的原因之一:如果您能够修改 String(从而更改其 hashCode),而该 String 是 HashMap 中的键,那么您将永远无法找到它,因为你最终会在错误的地方寻找它!

其他答案推荐 Joshua Bloch 的 Effective Java。如果您问这样的问题,那么现在是您职业生涯中购买这本书并从头到尾阅读的最佳时机。一两年后重新阅读它也是值得的,那时你会忘记其中的一些内容,而更多的内容会变得有意义......

== (used on objects rather than on primitive values) tests whether 2 objects are actually the same object; it compares whether the pointers are actually pointing to the same memory location.

.equals() is defined by the object itself.

String s1 = new String("Hello");
String s2 = new String("Hello");

boolean b1 = ( s1 == s2 ) ; // false: s1 and s2 point to different objects
boolean b2 = ( s1.equals(s2) ) ; // true: s1 and s2 both represent the same
                                 //       piece of text - "Hello"

.hashCode() is an optimisation trick (in most of its uses, anyway). A lot of code in the standard libraries makes the assumption that if o1.equals(o2)==true then o1.hashCode()==o2.hashCode() and that if o1.hashCode()!=o2.hashCode() then o1.equals(o2)==false in order to work faster.

The most obvious example of such an optimisation is the HashMap class. This makes retrieving objects using a key really fast, but breaks badly if hashCode and equals don't work properly for the key elements. In fact, this is one of the reasons that the String class is immutable: if you were able to modify a String (and so change its hashCode) while that String was the key in a HashMap, then you would never be able to find it, since you would end up looking for it in the wrong place!

Other answers recommend Effective Java by Joshua Bloch. If you are asking such questions, then now is the perfect time in your career to buy the book and read it cover to cover. It'll also be worth re-reading it in a year or two's time, when you'll have forgotten some of it and more of it will make sense...

雨轻弹 2024-10-16 03:48:19

== 运算符 -->检查天气 2 引用是否指向同一个对象。如果相同则返回 true,否则返回 false。

equals( ) -->检查引用对象和状态对象。听到状态意味着对象数据。在此任何一个为 true 时都会返回 true。否则为假。但是我们必须在用户定义的对象中重写 equals( ) 并编写适当的代码。

Hashcode( ) --> 对象的 hashCode 只是代表一个随机数,JVM 在将对象保存/添加到哈希集、哈希表或哈希映射时可以使用该随机数。

hashcode() 示例

class TestHasChode
{
int i;
TestHasChode(int i)
{
this.i = i;
}

public static void main(String arg[])
{  
    //before overriding hashcode()  
TestHasChode t1 = new TestHasChode(100);   
TestHasChode t2 = new TestHasChode(110);

System.out.println(t1); //TestHasChode@45e41830  
System.out.println(t2); //TestHasChode@1f01b29  

TestHasChode t3 = new TestHasChode(100);  
TestHasChode t4 = new TestHasChode(100);  
System.out.println(t3); //TestHasChode@3a8721bd   
System.out.println(t4); //TestHasChode@7db81d4f

/*hashCode() of Object class implemented to return hashCode based on address of an object, but based
on our requirement we can override hashCode() to generate our own numbers as hashCodes*/

//after overriding hashcode()  
System.out.println(t3); //TestHasChode@64  
System.out.println(t4); //TestHasChode@64  
}  
public int hashCode(){
return i;
}  
}  
-->Example of equals()method      
class Student
{
String name;   
int rollno;   
Student(String name,int rollno)
{   
this.name = name;    
this.rollno = rollno;   
}   
public static void main(String arg[])
{       
    //before overrideng equals method    
Student s1 = new Student ("raju", 101);     
Student s2 = new Student ("giri", 102);     
Student s3 = new Student ("giri", 102);     
System.out.println(s1.equals(s2));//false    
System.out.println(s2.equals(s3));//false    
    //after overriding equals method    
System.out.println(s1.equals(s2));//false    
System.out.println(s2.equals(s3));//true-->hear overriding equals() checks state.so it is true.  
    //in string variables comparisition   
    String s4="hello";    
    String s5=new String("hello");    
    String s6=new String("hello");   
System.out.println(s4.equals(s5));//true--> because String class containg overridden equals method   
System.out.println(s5.equals(s6));//true-->even though differnet object reference but String class containg overridden equals method   

}     
public boolean equals(Object obj){   
String name1 = this.name;   
int rollno1 = this.rollno;   
Student s2 = (Student)obj;     
String name2 = s2.name;     
int rollno2 = s2.rollno;    
if(name1.equals(name2) && rollno1 == rollno2){   
return true;}   
else{     
return false;}  
}        
}

== operator --> checks weather 2 references point to the same object or not. If same it return true otherwise false.

equals( ) --> checks both reference and state object. Hear state means object data. In this any one is true it returns true. Otherwise false. But we have to override equals( ) in our user defined object and write the appropriate code.

Hashcode( ) -->hashCode of an Object just represents a random number which can be used by JVM while saving/adding Objects into Hashsets, Hashtables or Hashmap.

Example of hashcode()

class TestHasChode
{
int i;
TestHasChode(int i)
{
this.i = i;
}

public static void main(String arg[])
{  
    //before overriding hashcode()  
TestHasChode t1 = new TestHasChode(100);   
TestHasChode t2 = new TestHasChode(110);

System.out.println(t1); //TestHasChode@45e41830  
System.out.println(t2); //TestHasChode@1f01b29  

TestHasChode t3 = new TestHasChode(100);  
TestHasChode t4 = new TestHasChode(100);  
System.out.println(t3); //TestHasChode@3a8721bd   
System.out.println(t4); //TestHasChode@7db81d4f

/*hashCode() of Object class implemented to return hashCode based on address of an object, but based
on our requirement we can override hashCode() to generate our own numbers as hashCodes*/

//after overriding hashcode()  
System.out.println(t3); //TestHasChode@64  
System.out.println(t4); //TestHasChode@64  
}  
public int hashCode(){
return i;
}  
}  
-->Example of equals()method      
class Student
{
String name;   
int rollno;   
Student(String name,int rollno)
{   
this.name = name;    
this.rollno = rollno;   
}   
public static void main(String arg[])
{       
    //before overrideng equals method    
Student s1 = new Student ("raju", 101);     
Student s2 = new Student ("giri", 102);     
Student s3 = new Student ("giri", 102);     
System.out.println(s1.equals(s2));//false    
System.out.println(s2.equals(s3));//false    
    //after overriding equals method    
System.out.println(s1.equals(s2));//false    
System.out.println(s2.equals(s3));//true-->hear overriding equals() checks state.so it is true.  
    //in string variables comparisition   
    String s4="hello";    
    String s5=new String("hello");    
    String s6=new String("hello");   
System.out.println(s4.equals(s5));//true--> because String class containg overridden equals method   
System.out.println(s5.equals(s6));//true-->even though differnet object reference but String class containg overridden equals method   

}     
public boolean equals(Object obj){   
String name1 = this.name;   
int rollno1 = this.rollno;   
Student s2 = (Student)obj;     
String name2 = s2.name;     
int rollno2 = s2.rollno;    
if(name1.equals(name2) && rollno1 == rollno2){   
return true;}   
else{     
return false;}  
}        
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文