0

how to pass the value of a 2-d array index to a 1-d array index in android?I want to place this code inside a switch case.

int r1[]= int M[0][0];

  • Just to undertstand: You have a 2D array (for example 3x4) and you want to put all values in a 1D array? – CloudPotato Jun 13 '16 at 09:26
  • Possible duplicate of [How to flatten 2D array to 1D array?](http://stackoverflow.com/questions/2569279/how-to-flatten-2d-array-to-1d-array) – psiyumm Jun 13 '16 at 09:38
  • no i want to add specific 2-d elements to 1-d arrays. `case R.id.b1: int r1=M[0][0]; B1.setClickable(false); break; case R.id.b2: [1][0]; int c2=M[1][0]; B1.setClickable(false); break;` something like this @Blobonat –  Jun 13 '16 at 09:52

1 Answers1

0

You want to flatten the array

Dependent on what version you are using these are a couple options!

Using Java 8 Streams:

int[] r1= Stream.of(M).flatMapToInt(IntStream::of).toArray();

Older versions of Java:

int[] r1 = new int[size];
int index = 0;
for (int[] x: M) {    // loop through the rows
    for (int y: x)    // loop through the values
        array[index++] = y;
}

Dynamically allocating the values using an ArrayList is an option:

ArrayList<int> r1 = new ArrayList<>();
case R.id.b1:
    int val=M[0][0]; 
    r1.add(val);
Small Legend
  • 733
  • 1
  • 6
  • 20
  • I want to pass specific values in specific cases `case R.id.b1: int r1=M[0][0]; B1.setClickable(false); break; case R.id.b2: [1][0]; int c2=M[1][0]; B1.setClickable(false); break;` is there any easy way to do this? –  Jun 13 '16 at 09:44
  • So maybe an ArrayList would be the better option here as you can dynamically allocate values this way and it won't be necessary to assign a fixed value to the array @beard_beer_code – Small Legend Jun 13 '16 at 09:56
  • How would that go? any help would be appreciated @Small Legend –  Jun 13 '16 at 09:58