简体   繁体   中英

How does HashSet check two objects?

class TestA extends Foo{
   private String a;
   private String b;
   private String c;

   public int hashcode() {
     // Use some inbuilt hashcode generator over a, b, c.
   }

   public boolean equals(Object a) {
     // a, b, c instance variables should match
   }
}
class TestB Extends Foo{
   private String a;
   private String b;
   private String c;

   public int hashcode() {
     // Same as Test A class implementation
   }

   public boolean equals(Object a) {
     // Same as Test A class implementation
   }
}

Say I add the following object into a HashSet:

TestA a = new TestA("a", "b", "c")

set.add(a);

Now, if I check the following object b is in the hashset, will set.contains(b) always return true?

TestB B = new TestB("a", "b", "c")

由于您的 HashSet 应该是HashSet<TestA>您甚至不应该能够将传递的 TestB 实例作为参数编译到contains 中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM