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 effic开发者_运维百科ient?) to extend the HashSet implementation in Java?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.
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?
An Integer List would work in this case:
Set<List<Integer>> s = new HashSet<List<Integer>>();
s.add((List<Integer>)Arrays.asList(new Integer[] {2,4}));
s.add((List<Integer>)Arrays.asList(new Integer[] {2,4}));
s.add((List<Integer>)Arrays.asList(new Integer[] {2,5}));
ThehashCode() and equals()
helpers are built into the ArrayList
class.
精彩评论