HashSet get() and contains() methods, by value or reference?
806562May 4 2011 — edited May 5 2011All 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?