简体   繁体   English

Java 2d对象数组

[英]Java 2d array of objects

I have a cell object with function 我有一个具有功能的单元格对象

public class Cell {
    static int X;
    static int Y;
    static int Val = 0;
    static int Player = 0;

    public Cell(int a, int b, int p) {
        // TODO Auto-generated constructor stub
        X = a;
        Y = b;
        Val = 0;
        Player = p;
    }

With additional function updateX, updateY, updateVal, updatePlayer and respective get functions. 使用附加功能updateX,updateY,updateVal,updatePlayer和相应的get函数。 It is called by 被称为

    Cell[][] grid = new Cell[7][6];
    for(int i = 0; i < 7; i++)
            for(int j = 0; j < 6; j++)
            {
            grid[i][j] = new Cell(i, j, 0);         
            }       
        System.out.println("wasd");
        grid[0][1].updatePlayer(1); 
        grid[0][1].updateVal(1);

        System.out.println("grid[0][1].getval = " + grid[0][1].getVal() + " grid[1][1].getval = " + grid[1][1].getVal());

But the output is 但是输出是

grid[0][1].getval = 1 grid[1][1].getval = 1

and should be 并且应该是

grid[0][1].getval = 1 grid[1][1].getval = 0

What is causing this error? 是什么导致此错误?

You made the X, Y, Val and Player variables in the class static. 您已将类中的X,Y,Val和Player变量设为静态。 Which means they are shared by all instances of that class, which means their values in all those instances will be exactly the same. 这意味着它们被该类的所有实例共享,这意味着它们在所有这些实例中的值将完全相同。 I'm pretty sure you wanted to declare those as instance variables instead: 我很确定您想将它们声明为实例变量:

public class Cell {
    private int x, y, val, player;
    // ...
}

You made Val a static variable, so only one Val variable exists and it is shared by all Cell objects. 您将Val静态变量,因此仅存在一个Val变量,并且所有Cell对象都共享它。

change: 更改:

static int Val = 0;

to: 至:

int Val = 0;

Similarly if you want individual Cell objects to retain separate instances of your variables (ie x,y,Val) you need to take away the static keyword from all of them 同样,如果您希望单个Cell对象保留变量的单独实例(即x,y,Val),则需要从所有变量中删除static关键字。

static int X;
static int Y;
static int Val = 0;
static int Player = 0;

These properties should not be static,following code should be ok: 这些属性不能是静态的,以下代码应该可以:

int X;
int Y;
int Val;//the default int value is zero 
int Player;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM