我想存储二维值,即B-1、C-2、D-3等。
对可以使用的类或接口有什么建议吗?
发布于 2009-10-14 03:38:37
多维数组有三种基本类型:
Java没有本机多维数组类型。Java有数组组成的数组,这不完全是一回事。例如,这是合法的Java:
int arr[][] = new int[] {
new int[3],
new int[4],
new int[5]
};固定的数组可以通过这种方式来完成,但它可能会很笨拙。将一维数组与对象包装器一起使用通常更容易:
public class Chessboard {
public final static DEFAULT_X = 8;
public final static DEFAULT_Y = 8;
public final static DEFAULT_SIZE = DEFAULT_X * DEFAULT_Y;
private final int x;
private final int y;
private final int size;
private final Piece squares[];
public Chessboard() {
this(DEFAULT_X, DEFAULT_Y);
}
public Chessboard(int x, int y) {
if (x < 2) {
throw new IllegalArgumentException("x (" + x + ") must be 2+");
}
if (y < 2) {
throw new IllegalArgumentException("y (" + y + ") must be 2+");
}
this.x = x;
this.y = y;
size = x * y;
pieces = new Piece[size];
}
public Piece get(int x, int y) {
return pieces[y * this.x + x];
}
public Piece get(String xy) {
// eg 'h3' => (7,2)
return get(xy.charAt(0) - 'a', xy.charAt(1) - '0');
}
// etc
}当然,这可以使用数组的数组来完成。
稀疏数组倾向于在Java中使用map实现:
public class Sparse2DArray<T> {
public final static int MAX_X = 8192;
public final static int MAX_Y = 8192;
private final Map<String, T> array = new HashMap<String, T>();
private final Pattern XY = Pattern.compile("^([A-Za-z]+)([0-9]+)");
public T get(int x, int y) {
if (x < 0 || x >= MAX_X) {
throw new IllegalArgumentException("x (" + x + ") must be 0 to " + (MAX_X-1));
}
if (y < 0 || y >= MAX_Y) {
throw new IllegalArgumentException("y (" + y + ") must be 0 to " + (MAX_Y-1));
}
return array.get(x + "," + y);
}
public T get(String xy) {
Matcher m = XY.matcher(xy);
if (!m.matches()) {
throw new IllegalArgumentException("xy (" + xy + ") must be letters followed by digits");
}
String s = m.group(1).toUpperCase();
int multiplier = 1;
int x = 0;
for (int i=s.length()-1; i>=0; i--) {
x += (s.chartAt(i) - 'A') * multiplier;
multiplier *= 26;
}
int y = Integer.valueOf(m.group(2));
return array.get(x, y);
}
// etc
}您也可以通过构造一个N维键类作为映射键来实现这一点。它需要定义适当的equals()和hashCode()方法,并且可能是一个更干净的解决方案,但上面的方法将会起作用。
显然,如果要将100x100数组的每个值都存储在稀疏数组类中,将会产生开销(因为所有映射都有开销)。这带来了密集数组。稀疏数组只存储设置值的值。密集数组存储每个可能键的值(在指定范围内)。
另外,密集数组类似于固定数组,但不完全相同。固定数组一旦创建就很难扩展(嗯,这是一个昂贵的操作,所以通常是不允许的),而密集数组可能是为扩展而构建的,就像您可以将它们用于电子表格和扩展最大X和Y值一样,因为用户使用的单元格越来越多,所以您定义了一个包含所有使用的值的矩形。
发布于 2009-10-14 02:34:47
如果您正在寻找一个电子表格类型的应用程序(可能是错误地从spring-framework标记和B-1/C-2名称中推断出来的),那么稀疏数组可能是最佳选择。
Colt就有一个这样的实现。
我回答了一个类似的问题here。
发布于 2009-10-14 02:33:47
我假设您需要Java中的一个数据结构来存储这些值。
您可以使用以下语法在Java中定义一个2D数组。
String[][] strArr = new String[5][5]; //defines a 5*5 String array
String[][] strArr2 = new String[1][2]; //defines a 1*2 String array 请注意,数组只能包含1个数据类型的值。可以使用下面的命令取消引用特定的项
System.out.println(strArr2[0][1]);对于您的特定示例,您还可以使用java.util.Map类并将数据存储为键-值对,但这要求“键”是唯一的。例如,
Map<String,Integer> keyval = new HashMap<String, Integer>();
keyval.put("B",1);
keyval.put("C",2);
keyval.put("D",3);
keyval.put("D",4); //wrong. will overwrite the previous entry.https://stackoverflow.com/questions/1563949
复制相似问题