File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Best structure for non-duplicate pairs? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Best structure for non-duplicate pairs?" Watch "Best structure for non-duplicate pairs?" New topic

Best structure for non-duplicate pairs?

bryan nelson
Ranch Hand

Joined: Jun 16, 2003
Posts: 95

I am in need of finding the best way to store a bunch of paired int values that can not be duplicates. For example, I can have a {3, 3} and a {3, 4} and a {4, 3}, but I will never have more than one of each of those.

Is there some kind of inherent structure in Java that would be ideal for me to use?

Thank you very much!

"...and the Truth will set you free."
Julien Grenier
Ranch Hand

Joined: Sep 01, 2005
Posts: 41
Well you can use the Set object to store your pair. This will assure the non-duplicate. then you need to code your Pair structure (a class with two field and you need to override the equals() and hashCode() methods and implements the Comparable interface

the coding of those methods is left as an exercise.
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Perhaps you can use java.awt.Point for your pairs.
Also, I don't see an immediate need for pairs to be
Comparable, certainly HashSet doesn't care.

There is no emoticon for what I am feeling!
bryan nelson
Ranch Hand

Joined: Jun 16, 2003
Posts: 95
I'm thinking that a Set using java.awt.Point objects would be just about perfect!

Thank you both!

Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Set is perfect. There is already an implementation in the form of HashSet. You can control its behavior in how you implement equals and hashcode. read Object to find out how.

Implement Comparable if you want to be able to sort the set with something like Collections.getSortedSet(Set s) or some such, as by default Sets are not ordered.
I agree. Here's the link:
subject: Best structure for non-duplicate pairs?
It's not a secret anymore!