Java: Adding to an array list
public class Maze
{
public static final int ACTIVE = 0;
public static final int EXPLORER_WIN = 1;
public static final int MONSTER_WIN = 2;
private Square[][] maze;
private ArrayList<RandomOccupant> randOccupants;
private Explorer explorer;
private int rows;
private int cols;
public Maze(Square[][] maze, int rows, int cols, int numTreasures, int numMonsters, String name)
{
int i;
this.maze = maze;
this.cols = cols;
this.rows = rows;
randOccupants = new ArrayList<RandomOccupant>();
for (i = 0; i < numTreasures; i++)
{
randOccupants.add(i) = new Treasure(this); //COMPILE ERROR
}...
Why can't I add this to th开发者_运维百科e arraylist? I believe the java docs says that I'm doing this correctly.
You can do either:
randOccupants.add( i, new Treasure(this) );
...or...
randOccupants.add( new Treasure(this) );
Both are equivalent, since you're always appending the new element to the end of the array.
See https://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html.
First, Treasure would need to either inherit from RandomOccupant or implement it (if it is an interface).
Second, if you want to add it at a particular point in the list, the syntax is
randOccupants.add(i,new Treasure(this));
Although it's hard to see why you don't just do
randOccupants.add(new Treasure(this));
since the items will be added in order even if you don't specify a location.
You're trying to add a Treasure to an ArrayList of RandomOccupants, so unless Treasure is a RandomOccupant, that's not going to work. The given code does not make it clear whether Treasure is a subclass of RandomOccupant, so it's not possible from the code here to say whether that's part of the problem.
What you're actually doing is adding an int to the list here, which is definitely not a RandomOccupant.
ArrayList's add() method returns either boolean or void depending on the version that you're using, so you can't assign to it. You're using the method incorrectly.
The two versions of add() are:
boolean add(E e)
void add(int index, E element)
The second version inserts the element at the specified position, and the first one inserts it at the end. Presumably, what you're intending to do is this:
for(i = 0; i < numTreasures; ++i)
randOccupants.add(new Treasure(this));
But of course, that assumes that Treasure is a subclass of RandomOccupant. If it isn't, then you'll need to change the type of the ArrayList for it to hold Treasures.
Because it is not a RandomOccupant.
Because you're using the add method wrong. You would call:
randOccupants.add(new Treasure(this));
精彩评论