我应该使用哪种类型的集合来解决这个Java问题?

时间:2011-06-15 14:08:27

标签: java collections

我想要一个只包含整数的二维数组。坐标也是整数。

问题是:

  • 我不知道会提前有多少列/行。
  • 我想随意填写。

示例:

假设第一个数字为2,放在(3;2)中。我希望能够简单地添加8,例如:array.add(8,2,1);

_ _ _ _      _ _ _ _
_ _ _ _  =>  _ _ 8 _
_ _ _ 2  =>  _ _ _ 2

我已经找到了一些实际可行的东西,但它真的很重。它是

Hashtable<Integer, Hashtable<Integer, Integer>>

有没有人看到更复杂的方法呢?我对收藏品并不是那么好。

7 个答案:

答案 0 :(得分:3)

也许你可以使用Guava的Table 这为你提供了table.put(R rowKey,C columnKey,V value)

Guava Table

答案 1 :(得分:2)

在这种情况下,您需要一些自定义类。如何定义Cell类:

public class Cell implements Comparable<Cell> {
    public int row;
    public int col;

    public Cell() {
        this(0, 0);
    }

    public Cell(int row, int col) {
        this.row = row;
        this.col = col;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + this.row;
        result = prime * result + this.col;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instance of Cell))
            return false;
        Cell cell = (Cell) obj;
        return this.row == cell.row && this.col == cell.col;
    }

    //Define ordering for cells
    @Override
    public int compareTo(Cell cell) {
        int compare = cell.row - this.row;
        if (compare == 0)
            compare = cell.col - this.col;
        return compare;
    }
}

然后是一个Grid类,它扩展TreeMap以维护逻辑单元格排序:

import java.util.TreeMap;

public class Grid extends TreeMap<Cell, Integer> {
    public Integer get(int row, int col) {
        return this.get(new Cell(row, col));
    }

    public Integer put(int row, int col, Integer value) {
        return this.put(new Cell(row, col), value);
    }
}

答案 2 :(得分:1)

制作适合您需求的课程。或者更好的是,创建一个接口,声明您希望使用该类的方法。在您的代码中,请参阅接口的类型。

在接口的实现中,我会使用ArrayList<ArrayList<Integer>>。在阅读或分配号码之前,只需检查坐标是否有效。如果没有,您应该能够在设置或读取值之前使用null(或其他非数字值)预填充数组。

答案 3 :(得分:1)

难道您不能只创建一个具有字符串键的哈希映射并存储您想要的任何数值吗?即

Map<String, Integer> m = new HashMap<String,Integer>();
m.put(makeKey(3,2), 2); // where makeKey returns something like "[3,2]"

编辑:

缺点是您没有可靠的迭代顺序,即如果您想迭代第N行或第N列中的所有内容,则没有简单的方法可以有效地执行此操作。

答案 4 :(得分:0)

Trove中查看TIntIntHashMap。那些Trove系列非常好。

答案 5 :(得分:0)

我猜你应该看二维数组或任何一个arraylists,因为你不知道它们的大小。

答案 6 :(得分:0)

整数列表列表可以使用。

List<List<Integers>

您可以通过索引执行行和列值。

相关问题