AGe*_*eek 7 java multidimensional-array data-structures
我想实现一个2-D数组的东西.
什么数据结构最适合这个?数组或其他数据结构都可以.如果有任何其他数据结构满足我的要求,请告诉我.
我不想使用数组,因为2-D数组需要在程序的早期声明,但它不是固定的; 大小将在运行时确定.
此外,行数将等于列数; 这是固定的,因为行和列都将使用相同的名称.
我也希望遍历这个二维数据结构,就像我通过Map一样.
听起来你想要使用行键,col键,然后使用该位置的值.没有内置的数据结构可以为您做到这一点.
最简单的使用方法可能是实际数据的二维数组.使用以下内容从行或列名称到数组中的实际索引.根据需要添加任意数量的名称到索引绑定.
Map<String, Integer> rows = new HashMap<String, Integer>();
Map<String, Integer> cols = new HashMap<String, Integer>();
Run Code Online (Sandbox Code Playgroud)
然后在网格中获取该值...
grid[rows.get("Row name")][cols.get("Column name")];
Run Code Online (Sandbox Code Playgroud)
get(String rowName, String colName)如果您想要更干净的API,请将网格和方法放在类中.
编辑:我看到问题已经更新,看起来行和列的名称到索引对是相同的.所以这是一个更新版本:
class SquareMap<V> {
private V[][] grid;
private Map<String, Integer> indexes;
public SquareMap(int size) {
grid = (V[][]) new Object[size][size];
indexes = new HashMap<String, Integer>();
}
public void setIndex(String name, int index) {
indexes.put(name, index);
}
public void set(String row, String col, V value) {
grid[indexes.get(row)][indexes.get(col)] = value;
}
public V get(String row, String col) {
return grid[indexes.get(row)][indexes.get(col)];
}
}
Run Code Online (Sandbox Code Playgroud)
数组的大小可以在运行时调整。如果您的行/列大小变化不太频繁,并且数据也不太稀疏,那么数组是您的最佳选择。
class TwoDimArray {
public int[][] createArray(int nRows, int nCols) {
return new int[nRows][nCols];
}
public int[][] resizeArray(int[][] oldArray, int nRows, int nCols) {
int[][] newArray = new int[nRows][nCols];
for (int i=0; i<Math.min(oldArray.length, nRows); ++i)
for (int j=0; j<Math.min(oldArray[i].length, nCols); ++j)
newArray[i][j] = oldArray[i][j];
return newArray;
}
}
Run Code Online (Sandbox Code Playgroud)