Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 717
  • Last Modified:

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,
0
twibblejaway
Asked:
twibblejaway
  • 3
  • 2
  • 2
  • +1
1 Solution
 
Ajay-SinghCommented:
Use java.util.Set/java.util.HashSet
0
 
twibblejawayAuthor Commented:
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,
0
 
Ajay-SinghCommented:
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.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
twibblejawayAuthor Commented:
yeah, what is the syntax for extending something?  
0
 
hoomanvCommented:
Objects that are being added to a Set must implement hashCode() and equals() methods as well
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_22032063.html
0
 
Ajay-SinghCommented:
public class MyClass {
    public boolean equals(Object o) {
        // Write your logic here.
    }
}
0
 
keyurkarnikCommented:
Make sure you do the same for hashcode too.
Also, do NOT extend the equals() method, override it!!
0
 
hoomanvCommented:
twibblejaway
In case of duplicate or similar comments, you should always select the first comment posted
0

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now