Link to home
Start Free TrialLog in
Avatar of twibblejaway
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,
Avatar of Ajay-Singh
Ajay-Singh

Use java.util.Set/java.util.HashSet
Avatar of twibblejaway

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,
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.
yeah, what is the syntax for extending something?  
Avatar of hoomanv
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
public class MyClass {
    public boolean equals(Object o) {
        // Write your logic here.
    }
}
ASKER CERTIFIED SOLUTION
Avatar of keyurkarnik
keyurkarnik

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
twibblejaway
In case of duplicate or similar comments, you should always select the first comment posted