tags:

views:

97

answers:

2
+1  Q: 

Two Key HashSet?

I need a HashSet implementation where the elements are a pair of Integers
eg. Set s = { {1,2} , {3,4} , {1,4}}. Here the set s has 3 elements.

This kind of two key HashSet is needed in many situations like, I have a relation in my database where the candidate key is a combination of two columns.
Is there some library which already provides this? If no such implementation is available, then rather then implementing the entire data structure from scratch, will it be easier (and efficient?) to extend the HashSet implementation in Java?

+1  A: 

And won't it work to put an array with 2 elements as a member of the set? I.e.:

Set<int[]> s = new HashSet<int[]>();
s.add(new int[] {1,2});
s.add(new int[] {3,4});

or create a class CandidateKey which has two fields and a custom equals() and hashCode() methods?

That all said, are you sure you want to handle object-relational mapping (mapping from database to objects) yourself, rather than using a library like Hibernate or EclipseLink?

Bozho
Will this actually work? I would have thought that the default equals and hashCode implementation of an array would be identity-based.
Adamski
they are, but in some cases it might be sufficient - I don't know whether his is such. That's why added the suggestion about a new class, where equals and hashcode are implemented properly.
Bozho
The proposed int[] solution has a limitation. There is nothing that prevents you from adding arrays with fewer or more elements, e.g. int[] empty = new int[0]; or int[] triple = new int[] {1, 2, 3};.
matsev
@matsev - and nothing prevents you from having candidate keys with more than 2 columns ;)
Bozho
+7  A: 

For this requirement I would create a data holder with the 2 integers as attributes and provide equals and hashcode implementations. Then put those objects in the Set.

rsp