How access data in an array as if it were stored in a two dimension array?

时间:2018-03-25 20:56:34

标签: java arrays reference

In Java, I have data that needs to be accessed as a one dimension array some of the time and as a two dimension array at other times. In other words, I would like to be able to map the same data as both a normal array and as a two dimension array.

Since a two dimension array in Java is actually an array of arrays, I would like to elements in the array of arrays to references of elements from the one dimension array.

Something like:

int  height = 5;
int  width  = 10;
int  length = height * width;

int[]   oneD = new int[length];
int[][] twoD = new int[height][];

int i, j;
for (i = j = 0 ; i < height ; ++i, j += width)
{
    // Following Statement fails to compile.
    twoD[i] = oneD[j];  // assign reference, not value
}

The problem is that the statement "twoD[i] = oneD[j]" fails because of types do not match. The statement "twoD[i][0] = oneD[j]" failes because twoD[i] is null. "twoD[i][] = oneD[j]" also fails to compile.

In C++, this is an easy problem where you would create the array of arrays as an array of pointers and then set each element of the array of pointers to the address of an element in the one dimension array.

My questions are:

  1. Is there a way to map the array of arrays in the two dimension array so that each of the arrays is a section of the one dimension array? In other words, can you access the reference of an element in an array and assign it to an array of arrays element?

  2. Is this possible to do this in Java without writing a class that encapsulates the data and provides one and two dimensional indexing to the data?

  3. Or, is there a better way of accomplishing the equivalent thing using container classes instead of arrays?

Factors:

  • Using Java 8

  • Am not concerned if the two dimension array can provide the correct length for each array (of columns).

1 个答案:

答案 0 :(得分:2)

  1. 没有。在Java中,没有办法采用&#39;引用&#39;到阵列的中间。唯一的访问是通过正常索引。

  2. 你不需要写一个类:容器类适合这个。

  3. 是。如果您创建了ArrayList,那么您可以使用List.subList返回对原始列表的某个部分的引用。这里唯一的技巧是列表在你拿到子列表之前需要实际包含元素。

  4. 类似于:

    List<Integer> list = IntStream.range(0, 50).boxed().collect(toList());
    List<List<Integer>> sublists = IntStream.range(0, 5)
        .mapToObj(i -> list.subList(i * 10, (i + 1) * 10)).collect(toList());
    
    System.out.println(subLists.get(2));
    

    打印出[20,21,22,23,24,25,26,27,28,29]