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 开发者_如何学Calready 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?
Just check if the hashset contains you're object:
if (hashSet.contains(obj)) {
doWhateverWith(obj);
}
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.
If equals(..)
returns true
, then the objects are the same, so you can use the one you are trying to add to the set.
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.
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.
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.
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.
精彩评论