Passing an array to a Class not just a Method

Viewed 57

I have made this sample code to pass an array to and from a method, changing the original array in the process.

public class ArrayPasserMain {

    public static void main(String[] args) {
        int[] lifegrid = {0,1,2};
        ArrayPass(lifegrid);
        for (int i=0; i<3; i++) {
            System.out.println(lifegrid[i]);
        }
    }

    static void ArrayPass(int grid[]) {
        for (int i=0; i<3; i++) {
            System.out.println(grid[i]); 
            grid[i] = grid[i] + 3;
        }
    }
}

How can I write the method ArrayPass in another class with the same results, passing the array over, changing the values and passing it back?

1 Answers

Try:

public class ArrayPasserMain {

    public static void main(String[] args) {
        int[] lifegrid = {0,1,2};
        lifegrid = AnotherClass.changeValues(lifegrid);
    }
}

class AnotherClass {
    static int[] changeValues(int[] grid) {
        for (int i=0; i<grid.length; i++) {
            System.out.println(grid[i]); 
            grid[i] = grid[i] + 3;
        }
        return grid;
    }
}
Related