Steven F. Le Brun
Steven F. Le Brun

Reputation: 648

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

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:

Upvotes: 0

Views: 62

Answers (1)

sprinter
sprinter

Reputation: 27976

  1. No. In Java there is no way to take a 'reference' to the middle of an array. The only access is through through normal indexing.

  2. You don't need to write a class: container classes are fine for this.

  3. Yes. If you create, say an ArrayList then you can use List.subList to return a reference to a section of the original list. The only trick here is that the list needs to actually have elements in it before you take the sublists.

So something like:

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

Prints out [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

Upvotes: 2

Related Questions