1

I want to handle a set of objects of class (MyClass) in a HashSet. When I try to add an object that already exists (relying on equals an hashCode of MyClass), the method return false. Is there a way/method to get in return the actual object that already exists?

Please give me any advice to handle that collection of object be able to get the existing object in return when add returns false?

2
  • 4
    If you call add and it returns false, you should already HAVE the object - you tried to pass it in! Commented Aug 16, 2011 at 20:18
  • 2
    @Josh.trow While that is true, I guess what the OP wants is the object in that memory location, and not the logically equal object. Commented Aug 16, 2011 at 20:24

7 Answers 7

4

Just check if the hashset contains you're object:

if (hashSet.contains(obj)) {
 doWhateverWith(obj);
}
Sign up to request clarification or add additional context in comments.

3 Comments

The "== true" part is redundantly redundant.
This also doesn't answer the question. You still don't have the object in the set, just one that's equal to it.
contains will only return true if obj refers to the object in HashSet so, it will be in the set.
2

Short of iterating over the set, no, there is no way to get the existing member of the set that is equal to the value just added. The best way to do that would be to write a set wrapper around HashMap that maps each added value to itself.

Comments

1

If equals(..) returns true, then the objects are the same, so you can use the one you are trying to add to the set.

Comments

1

Why would you let it return the object which you're trying to add? You already have it there!

Just do something like:

if (!set.add(item)) {
    // It already contains the item.
    doSomethingWith(item);
}

If that does not achieve the desired result, then it simply means that the item's equals() is poorly implemented.

Comments

0

One possible way would be:

myClass[] myArray = mySet.toArray(new myClass[mySet.size]);
List myList = Arrays.asList(myArray);
MyClass myObject = myList.get(myList.indexof(myObject));

But of course as some people pointed out if it failed to get inserted, then that element is the element you are looking for, unless of course that you want what is stored in that memory location, and not what the equals and hashCode tells you, i.e. not the logically equal object, but the == object.

Comments

0

When using a HashSet, no, as far as I know you can't do that except by iterating over the whole thing and calling equals() on each one. You could, however, use a HashMap and just map every object to itself. Then call put(), which will return the previously mapped value, if any.

Comments

0

http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html#contains(java.lang.Object)

You can use that method to check if you like; but the thing you have to keep in mind is that you already have the object that exists.

Comments