How to pass a double array(boolean[][]) between activities?

前端 未结 3 1928
难免孤独
难免孤独 2021-01-25 00:34

I can\'t see to get a double boolean array to pass through to the another activity. I use putExtra and when I retrieve it and cast it to boolean[][], it states that

3条回答
  •  无人共我
    2021-01-25 01:25

    If you really require a 2-dimensional array, you can easily convert a 2-dimensional array into a single dimensional array for passing between Activities like so:

    public boolean[] toOneDimension(boolean[][] input){
        boolean[] output = new boolean[input.length * input[0].length];
    
        for(int i = 0; i < input.length; i++){
            for(int j = 0; j < input[i].length; j++){
                output[i*j] = input[i][j];
            }
        }
    
        return output;
    }
    

    which you can then build back into a 2-dimensional array like so:

    public boolean[][] toTwoDimensions(int dimensions, boolean[] input){
    
        boolean[][] output = new boolean[input.length / dimensions][dimensions];
    
        for(int i = 0; i < input.length; i++){
            output[i/dimensions][i % dimensions] = input[i];
        }
    
        return output;
    }
    

    then use like so:

    public static void main(String[] args){
        int size = 10;
    
        Random rand = new Random();
        Tester tester = new Tester(); //example code holder
        boolean[][] value = new boolean[size+1][size];
    
        for(int i = 0; i < size+1; i++){
            for(int j = 0; j < size; j++){
                value[i][j] = rand.nextBoolean();
            }
        }
    
    
        boolean [][] output = tester.toTwoDimensions(size, tester.toOneDimension(value));
    
        for(int i = 0; i < size+1; i++){
            for(int j = 0; j < size; j++){
                assert value[i][j] == output[i][j];
            }
        }
    
    
    }
    

    The only requirement is that you need to know the dimension of your array before you flattened it.

提交回复
热议问题