How to pass an array from one object to another in Java?

时间:2015-06-30 13:27:37

标签: java arrays

I have a class in which I'm trying to create a 2D array with a starting value of 0 in every space (class1). I want that array to be able to be called in another class (class2), edit the values and then be stored back in the original class (class1) that it was created in to be called in another class (class3) with the values that were changed from the second class.

I know there must be some way to do this but if it's too complicated or not an efficient way I can find another way do what I'm trying to accomplish. If you can give me an example that would be great.

Right now I have a small class with.

public class Inventory {

    public static int[][] inventory_1 = {
        {0, 0, 0, 0, 0, 0}, 
        {0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0},
    };
}

I'm using this temporarily as a placeholder for the array, but as expected it resets the contents to the original array when called from another class, or if a new instance of the second class is run.

Inventory inventorynew = new Inventory();
inventorynew.inventory_1 [0][0] = 1

What I'm actually doing is creating and inventory system and depending on what the value is in each place, it will determine what is in the inventory.

3 个答案:

答案 0 :(得分:6)

Inventory inventorynew = new Inventory();
inventorynew.inventory_1 [0][0] == 1

This is what you're doing wrong.

  • = : set a value

  • == : check a value

I suppose you are trying to set the value to 1, but you are checking if it is 1.

答案 1 :(得分:1)

From the code:

Inventory inventorynew = new Inventory();
inventorynew.inventory_1 [0][0] == 1

Would imply that you are checking that the item in inventorynew.inventory_1 [0][0] is equal to the value "1" as opposed to setting the value of that item to "1". Note the differences between:

  • a = b - Set a to equal b
  • a == b - Is a equal to b?

答案 2 :(得分:0)

I see 2 solutions :

  1. Pass it as parameter, and get it back as return value
  2. Use a List instead, all your changes will be kept unless you create a new List.

Edit : maybe you should take a look here : Is Java "pass-by-reference" or "pass-by-value"?