简体   繁体   English

独特的Java 2D Arraylist

[英]Unique Java 2D Arraylist

I am trying to create a unique 2d arraylist. 我正在尝试创建一个唯一的二维arraylist。 The number of columns are fixed and the number of rows should be dynamic. 列数是固定的,行数应该是动态的。 However, for the first column I want to have the type as chars. 但是,对于第一列,我希望将类型设置为chars。 The rest of the columns should be with int types. 其余的列应为int类型。 Is there a way of doing this? 有办法吗? I am using it for Arithmetic compression. 我将其用于算术压缩。

This is what I currently have 这是我目前所拥有的

    //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));
    }   

在此处输入图片说明

This is what you want... 这就是你想要的...

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));
} 

And the output is 输出是

Row = [a, 5, 6]
Row = [b, 5, 6]
Row = [7, 8]

Create a class that corresponds to your needs: 创建一个与您的需求相对应的类:

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();
    }
}

The object route is probably the best way for you. 对象路由可能是您的最佳方法。 Especially since an Arraylist / Arraylist isn't defined for primitives. 尤其是因为未为基元定义Arraylist / Arraylist。 You would need to use the Integer type. 您将需要使用Integer类型。

And even then, you would need 2 array lists, one for the integers and one for the characters. 即使这样,您仍需要2个数组列表,一个用于整数,一个用于字符。

See this question: Java Vector or ArrayList for Primitives for more about that. 请参见以下问题: 有关原始的Java Vector或ArrayList的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM