用于存储数据的适当数据结构

时间:2014-05-05 13:30:04

标签: java hashset

我应该存储以下数据,其中第一个整数是唯一的:

<118,15>
<429,15>
<625,30>

HashSet<Integer,Integer>是存储它的好方法吗?

4 个答案:

答案 0 :(得分:1)

Set是唯一性的,尽管key -> value集合中没有Set内容。所以,

HashSet<Integer,Integer>

根本不存在。

只要您有一个唯一的整数用作关键字,可能Map就是您所寻找的。

示例:

Map<Integer, Integer> map = new HashMap<>();
map.put(118, 15); //the key is 118, value is 15
map.put(429, 15);
map.put(625, 30);
map.get(118);     //get the value for the key 118, so it returns 15

您无法保证任何Integer的唯一性,您可以使用:

List<Integer[]> ints = new ArrayList<>();
ints.add(new Integer[] {185, 15});
ints.add(new Integer[] {429, 15});
ints.add(new Integer[] {625, 15});

修改

正如您通过审核解释的那样,第一个元素是唯一的,因此您可能对Map接口感到满意,因为它是它的主要目的。

答案 1 :(得分:0)

HashSet适用于key -> value之类的结构,其中key是唯一的。

如果您只想存储整数对,则必须创建自己的数据类型,如:

public class MyTuple /* here should be adequate name */ {
    int first, second; // there too
    public int getFirst() {
        return first;
    }
    public int getSecond() {
        return second;
    }
    public MyTuple(int first, int second) {
        this.first = first;
        this.second = second;
    }
}

如果你有点懒,可以使用Map.Entry来达到这个目的,但是在Java世界中它不正确,你应该有一个类用于一个目的,它应该重新修改它& #39;指定。

有些库有自己的Pair类实现,例如JavaFX,TestNG有一些。

所有这些都应该包含在数组或List中,例如:

List<MyTuple> tuples = new ArrayList<>();

答案 2 :(得分:0)

取决于使用情况。假设类型为int [](大小为2的数组):

- 如果您只想存储,请使用其中一个List实现(您的选择基本上在LinkedList和Vector之间,具体取决于插入模式)

- 如果你需要迭代一个有序的fasion,自定义TreeSet将起作用:

TreeSet<int []> set = new TreeSet<int[]>(new Comparator<int []>()
{
    public int compare(int[] o1, int[] o2) {return o1[0] != o2[0] ? o1[0]-o2[0] : o1[1]-o2[1];}
});

- 如果有很多查找,请使用HashSet

答案 3 :(得分:0)

Apache Commons Lang,有一个ImmutablePair,如果你愿意,可以放入SetSet在这种情况下是否有用,取决于您要对数据执行的操作。集合是可迭代的,但是无法读取(只能检查),值得一提的是默认情况下,在Set&lt; 100,13&gt;中。和&lt; 100,14&gt;不是同一个项目(即,如果你添加两个,你将有2个项目&#34;键&#34; 100)。此外,如果您关心排序,我可能会使用TreeSet / TreeMap。