Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

HashSet get() and contains() methods, by value or reference?

806562May 4 2011 — edited May 5 2011
All the tutorials I've seen on HashSets use Strings as the object type. With Strings, it seems the get() and contains() methods work by value, not by reference.

<CODE>
String s1 = "dog";
String s2 = "cat";
String s3 = "dog";

HashSet<String> set = new HashSet<String>();
set.add(s1);

System.out.println(set.contains(s1)); //true;
System.out.println(set.contains(s2)); //false
System.out.println(set.contains(s3)); //true
</CODE>

But when I use a custom object, it works by reference:

<CODE>
MyClass c1 = new MyClass("dog", 1);
MyClass c2 = new MyClass("cat", 1);
MyClass c3 = new MyClass("dog", 2);
MyClass c4 = new MyClass("dog", 1);

HashSet<MyClass> myClassSet = new HashSet<MyClass>();
myClassSet.add(c1);

System.out.println(myClassSet.contains(c1)); //true
System.out.println(myClassSet.contains(c2)); //false
System.out.println(myClassSet.contains(c3)); //false
System.out.println(myClassSet.contains(c4)); //false
</CODE>

("MyClass" is a simple class that holds a String and an int).

Is there any way I can get the set to select by value rather than reference for objects that aren't String?
If so, is it possible that the value test could be customised, so that, for example, the above will return true if the String in MyClass is the same, regardless of the int value?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 2 2011
Added on May 4 2011
5 comments
1,659 views