user735241
user735241

Reputation:

Java Collections-> Hashset

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?

Upvotes: 1

Views: 339

Answers (7)

Oscar Gomez
Oscar Gomez

Reputation: 18488

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.

Upvotes: 0

Dave
Dave

Reputation: 6189

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.

Upvotes: 0

BalusC
BalusC

Reputation: 1109695

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.

Upvotes: 1

Headshota
Headshota

Reputation: 21449

Just check if the hashset contains you're object:

if (hashSet.contains(obj)) {
 doWhateverWith(obj);
}

Upvotes: 4

Bozho
Bozho

Reputation: 597402

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

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120586

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.

Upvotes: 2

user8681
user8681

Reputation:

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.

Upvotes: 0

Related Questions