-2

So, if my values are:

123, 12.34

234, 23.34

345, 45.67

etc. like this,is it possible to use 2 dimension array to set up those values?

1 Answers1

1

Yes and no.

Technically you cannot define different static type per array dimension. So you cannot mix an int column with a double column. Even for objects you cannot mix an Integer column with a Double column.

If you just need primitives you can use double[][] as a double can represent all 32-bit integers (see Representing integers in doubles). But technically the array is all-doubles: nothing would prevent you from storing a value like 3.14 in the the first column.

For objects, you can use a common base type (if one exists). For your particular use case, all numerical types extend java.lang.Number therefore this works:

    @Test
    public void testMixedNumbersArray() {
        Number[][] array = new Number[3][2];
        array[0][0] = 123; array[0][1] = 12.34;
        array[1][0] = 234; array[1][1] = 23.34;
        array[2][0] = 345; array[2][1] = 45.67;
        for (Number[] x : array) {
            System.out.println(Arrays.toString(x));
        }
    }

// outputs:
// [123, 12.34]
// [234, 23.34]
// [345, 45.67]

Keep in mind that this will actually allow you to also mix Float, Short, ...or even BigDecimal values in this array, as well as allow null values.

Therefore, if you need tight control over the data type, an option would be to create a custom class that encapsulates two separate arrays of the appropriate type:

public class MyArray {
    int[] col1;
    double[] col2;

    public MyArray(int size) {
        col1 = new int[size];
        col2 = new double[size];
    }
    // ... add get/set methods as needed, e.g.

    public void setCol1(int pos, int value) {
        col1[pos] = value;
    }

    public void setCol2(int pos, double value) {
        col2[pos] = value;
    }
}

One last thing to keep in mind is that Java multi-dimensional arrays are "arrays of arrays" (see Multi-dimensional arrays in Java). This is why there is only a single type: that of the inner-most array. All other dimensions are just levels of indirection (arrays of arrays) on the way to the target array instance.

Alexandros
  • 2,097
  • 20
  • 27