twibblejaway
asked on
A unique collection
Hello,
I want to have a collection of objects(kind of). The problem I have is that things like the java Collection and Vector class allow me check to see if an object already exists in a given collection. What I actually want to check is to see if there is an object which has been initialized to the same values already in teh collection.
What would be the easiest way of doing this?
Thanks,
I want to have a collection of objects(kind of). The problem I have is that things like the java Collection and Vector class allow me check to see if an object already exists in a given collection. What I actually want to check is to see if there is an object which has been initialized to the same values already in teh collection.
What would be the easiest way of doing this?
Thanks,
Use java.util.Set/java.util.Ha shSet
ASKER
That has the same problem as the other 2 methods. It tests to see if the objects are the same, not if what they are initialized is equal. I think I need to write my own Contains function for one of these classes. I'm just not sure on the exact syntax of how to do that in java?
Can somebody show me an example.
Thanks,
Can somebody show me an example.
Thanks,
when collection framework checks if object already exists, it calls equals() method to figure out that.
You can extend equals() method of the java.lang.Object class to do that.
You can extend equals() method of the java.lang.Object class to do that.
ASKER
yeah, what is the syntax for extending something?
Objects that are being added to a Set must implement hashCode() and equals() methods as well
https://www.experts-exchange.com/questions/22032063/Problem-with-Hashtable.html
https://www.experts-exchange.com/questions/22032063/Problem-with-Hashtable.html
public class MyClass {
public boolean equals(Object o) {
// Write your logic here.
}
}
public boolean equals(Object o) {
// Write your logic here.
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
twibblejaway
In case of duplicate or similar comments, you should always select the first comment posted
In case of duplicate or similar comments, you should always select the first comment posted