我正在尝试创建一个独特的2d arraylist。列数是固定的,行数应该是动态的。但是,对于第一列,我希望将类型设为chars。其余列应该是int类型。有办法做到这一点吗?我用它进行算术压缩。
这就是我目前所拥有的
//encoding section
float low = 0;
float high = 1;
float range = high - low;
List<int[]> rowList = new ArrayList<int[]>();
rowList.add(new int[] { 1, 2, 3 });
rowList.add(new int[] { 4, 5, 6 });
rowList.add(new int[] { 7, 8 });
for (int[] row : rowList)
{
System.out.println("Row = " + Arrays.toString(row));
}
答案 0 :(得分:1)
这就是你想要的......
List<Object[]> rowList = new ArrayList<Object[]>();
rowList.add(new Object[] { 'a', 5, 6 });
rowList.add(new Object[] { 'b', 5, 6 });
rowList.add(new Object[] { 7, 8 });
for (Object[] row : rowList)
{
System.out.println("Row = " + Arrays.toString(row));
}
输出
Row = [a, 5, 6]
Row = [b, 5, 6]
Row = [7, 8]
答案 1 :(得分:0)
创建符合您需求的类:
public class My2DArray {
private char[] firstColumn;
private int[][] otherColumns;
// + constructor, getters, setters
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(int row = 0 ; row < firstColumn.length ; ++row) {
sb.append(firstColumn[row]);
for(int col = 0 ; col < otherColumns[row].length ; ++col) {
sb.append(", ").append(otherColumns[row][col]);
}
sb.append(System.getProperty("line.separator"));
}
return sb.toString();
}
}
答案 2 :(得分:0)
对象路线可能是最适合您的方式。特别是因为没有为基元定义Arraylist / Arraylist。您需要使用Integer类型。
即使这样,你也需要2个数组列表,一个用于整数,一个用于字符。
看到这个问题: Java Vector or ArrayList for Primitives了解更多相关信息。