I'm having a hard time figuring out how to pass by reference in Java. I currently have a class as follows
class Example {
ArrayList<Foo> list;
Bar hello;
Example(ArrayList<foo> list, Bar hello) {
this.list = list;
this.hello = hello;
}
}
In my main class, I initialize an array list of Foo, and a Bar object. Then I initialize Example passing in the array list and Bar objects. What I want is whenever the objects I passed to Example are updated in the Main class, they get updated in Example too. But for now, only ArrayList is updated. But Bar hello isn't. What makes ArrayList different from Bar that it updates but Bar doesn't?
Edit
Ok here's part of the actual code:
public class Main {
static int
board_n = 1, // amount of boards
rows = 8, // board width
cols = 8; // board height
static ArrayList<Board> boardlist;
static Player player1 = new Player("Mr");
static Player player2 = new Player("9000");
static Player currentPlayer = player1;
static Move dummy = null;
public static void main(String[] args) {
int random_row, random_col, random_board, rand_i;
Dimension size = new Dimension(rows, cols);
boardlist = new ArrayList(board_n);
for(int i = 0; i < board_n; i++) {
boardlist.add(new Board(i, size));
}
Rules rulez = new Rules(boardlist, dummy, currentPlayer);
rulez.setPieces();
Random generator = new Random();
while(rulez.getPiecesAvailable("Checker", player1.getName()) > 0 || rulez.getPiecesAvailable("Checker", player2.getName()) > 0) {
// initialize points and generate random location
random_row = generator.nextInt(rows);
random_col = generator.nextInt(cols);
random_board = generator.nextInt(board_n);
Point point = new Point(random_row, random_col);
// initialize pieces and randomly set moveable
Piece hello1 = new Checker(player1.getName(), Integer.toString(random_row), Integer.toString(random_col), Integer.toString(0), -1);
Piece hello2 = new Checker(player2.getName(), Integer.toString(random_row), Integer.toString(random_col), Integer.toString(0), 1);
// add piece to board
if(rulez.validateAddition(new Location(point, random_board), hello1))
boardlist.get(random_board).addPiece(hello1, point);
if(rulez.validateAddition(new Location(point, random_board), hello2))
boardlist.get(random_board).addPiece(hello2, point);
}
currentPlayer = player2;
}
}
When I create a Rules object, I pass boardlist, dummy, and currentPlayer to it. When I add stuff to boardlist, the boardlist inside Rules is the same one as the one outside. But on the last statement, when I change currentPlayer to player2, it doesn't change in Rules.