Finni
Finni

Reputation: 559

Are ArrayLists mutable?

I have a class containing the Arraylist ArrayList<Move> moves. I call the getter of that Arraylist from another class and add a move: panel.getMoves().add(move). But when I am iterating through the Arraylist afterwards, some really weird errors occur, hinting to the moves not being added correctly.

Do I have to call panel.setMoves(panel.getMoves().add(move))? If so, why, I always thought Lists were mutable?

Upvotes: 1

Views: 5152

Answers (1)

Andrew
Andrew

Reputation: 49626

It depends on how getMoves() is implemented.

It could return a copy of the internal ArrayList (you have to call setMoves(ArrayList) in order to update it), or publish a direct reference to it (you don't need the setter). The latter indicates bad encapsulation, though.

Any instance of the class ArrayList is mutable. It's basically a wrapper over a dynamically-sized array. Its elements can be modified.

Upvotes: 6

Related Questions