0

I am trying to create a unique 2d 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. The rest of the columns should be with int types. 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));
    }   

enter image description here

Jason C
  • 38,729
  • 14
  • 126
  • 182
statius
  • 33
  • 5

3 Answers3

1

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]
Mohammad Najar
  • 2,009
  • 2
  • 21
  • 31
0

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();
    }
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • Shouldn't this be done the other way around? Creating a class `Row` that contains a character and an array of integers. Here you assign much responsibility to one class. – Willem Van Onsem Mar 12 '14 at 20:20
0

The object route is probably the best way for you. Especially since an Arraylist / Arraylist isn't defined for primitives. You would need to use the Integer type.

And even then, you would need 2 array lists, one for the integers and one for the characters.

See this question: Java Vector or ArrayList for Primitives for more about that.

Community
  • 1
  • 1