Two Key HashSet?

问题描述 投票:4回答:3

我需要一个HashSet实现,其中的元素是一对整数例如。 Set s = { {1,2} , {3,4} , {1,4}}。这里set包含3个元素。

在许多情况下都需要这种两个键的HashSet,例如,我的数据库中有一个关系,其中候选键是两列的组合。是否有一些已经提供此功能的库?如果没有可用的此类实现,那么从头开始实现整个数据结构,是否会更容易(更有效?)来扩展Java中的HashSet实现?

java hashset
3个回答
8
投票

为此,我将创建一个以2个整数作为属性的数据持有人,并提供equals和hashcode实现。然后将这些对象放入集合中。


1
投票

而且将包含2个元素的数组作为集合的成员会起作用吗?即:

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

或创建具有两个字段以及自定义CandidateKeyequals()方法的类hashCode()

话虽如此,您确定要自己处理对象关系映射(从数据库到对象的映射),而不要使用像Hibernate或EclipseLink这样的库吗?


0
投票

在这种情况下,整数列表将起作用:

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}));

[hashCode() and equals() helpers内置在ArrayList类中。

© www.soinside.com 2019 - 2024. All rights reserved.