У меня проблема, которую я пытался решить несколько дней. Проблема в том, что когда я создаю список объектов ArrayList, в конце концов, все они равны последнему объекту. Я считаю, что это как-то связано с постоянным добавлением одного и того же объекта, но, насколько я могу судить, я каждый раз создаю новый.
Смысл этой программы должен заключаться в создании группы различных ячеек или в целях моделирования (людей), которые впоследствии могут взаимодействовать друг с другом в зависимости от своих случайных атрибутов.
Это код, с которым у меня проблемы
private ArrayList<Cell> cellsList = new ArrayList<Cell>(); //This appears before the Class is created
private int startingCellNumber = 10; //This appears before the Class is created
//This is inside the class
//Go through and create the starting cells
for(int index=0; index < startingCellNumber; index++) {
cellsList.add(new Cell());
}
Любая помощь будет принята с благодарностью, я знаю, что есть вопросы, похожие на этот, о переполнении стека, но все ответы на них не устранили мою проблему.
Оба полных кода (написаны на Java Processing) Бегун
private ArrayList<Cell> cellsList = new ArrayList<Cell>();
private int startingCellNumber = 10;
void setup() {
//Set up the background stuff
size(600,400);
frameRate(30);
noStroke();
//Go through and create the starting cells
for(int index=0; index < startingCellNumber; index++) {
//Cell newCell = new Cell();
cellsList.add(new Cell());
System.out.println(index + " : " + cellsList.get(index).getColonyColor() + " : (" + cellsList.get(index).getLocation(0) + "," + cellsList.get(index).getLocation(1) + ")"); //Here to test the output
}
System.out.println("------------------");
//Test to see where error lies
for(int index=0; index < startingCellNumber; index++) {
System.out.println(index + " : " + cellsList.get(index).getColonyColor() + " : (" + cellsList.get(index).getLocation(0) + "," + cellsList.get(index).getLocation(1) + ")");
}
}
void draw() {
//Refresh the background
background(51);
//Go through and draw all of the cells (will be moved to the draw function)
for(Cell activeCell : cellsList) {
activeCell.drawCell();
//System.out.println(activeCell);
}
}
Класс ячейки
private int strength;
private int age;
private int reproduction;
private String colonyColor;
private boolean disease;
private int[] location = {0,0};
private String[] directions = {"LEFT","Right","Up","Down"};
class Cell {
//This is the constructor for the cell class
Cell() {
strength = (int)(Math.random()*8)+3;
age = 0;
reproduction = (int)(Math.random()*6)+0;
colonyColor = pickColor();
if (colonyColor.equals("BLUE")) { location[0] = (int)(Math.random()*591)+0; location[1] = (int)(Math.random()*391)+0; }
else if (colonyColor.equals("RED")) { location[0] = (int)(Math.random()*591)+0; location[1] = (int)(Math.random()*391)+0; }
}
//This class will randomly pick a team color for the cell
private String pickColor() {
int randColorNum = (int)(Math.random()*2)+1;
if (randColorNum == 1) { return "BLUE"; }
else if (randColorNum == 2) { return "RED"; }
else { return "BLUE"; }
}
//This method picks the direction in which the cell will move
private void moveDirection() {
String chosenDirection = directions[(int)(Math.random()*4)+0];
if (chosenDirection.equals("Left")) { checkNewLocation(-1,0); }
}
//this method uses the direction given by moveDirection() and decides what to do with it
private void checkNewLocation(int xChange,int yChange) {
}
public void drawCell() {
//Changes color depending on cells colonyColor
if (getColonyColor().equals("RED")) { fill(255,0,0); }
else { fill(0,0,255); }
//Should draw the cell
//System.out.println(getLocation(0) + " " + getLocation(1));
rect(getLocation(0), getLocation(1), 10, 10);
}
//All of the gets and set methods for the Cell class's variables
public int getStrength() { return strength; }
public void setStrength(int s) { strength = s; }
public int getAge() { return age; }
public void setAge(int a) { age = a; }
public int getReproduction() { return reproduction; }
public void setReproduction(int r) { reproduction = r; }
public String getColonyColor() { return colonyColor; }
public void setColonyColor(String c) { colonyColor = c; }
public boolean getDisease() { return disease; }
public void setDisease(boolean d) { disease = d; }
public int getLocation(int index) { return location[index]; }
}
Я попытался добавить начальное целое число индекса к классу ячейки, а затем сделать его параметром, чтобы сделать его другим для всех 10 ячеек, но это не сработало.
Покажите, пожалуйста, код класса Cell
Судя по опубликованному вами коду, это правильно. new Cell() всегда одинаковый
Я пытаюсь заставить new Cell () каждый раз создавать новую ячейку.
@NiVeR посмотрите на конструктор класса ячейки. Я думаю, он рандомизирует ценности.
Вы пробовали печатать сам объект вместо его полей? Я сомневаюсь, действительно ли это один и тот же объект, или это просто случайные числа, возвращающие одинаковые значения. System.out.println(cellsList.get(index)) в одной из формовок setup
У меня есть, и вот что я получил от него Runner $ Cell @ 73337102 Runner $ Cell @ 197d27c8 Runner $ Cell @ 110cd60a Runner $ Cell @ 6021c414 Runner $ Cell @ 8721273 Runner $ Cell @ 784127d2 Runner $ Cell @ 7a90d40a Runner $ Cell @ 59467c50 Бегун $ Cell @ 3da6abf6 Бегущий $ Cell @ fffd473




Проблема с моим кодом заключалась в том, что я создал все переменные класса Cell до строки class Cell { }. Перемещая их после линии, все работало нормально.
Вы переопределили equals в классе Cell? Возможно, используя конструктор без параметров для создания 10 экземпляров Cell, было создано 10 экземпляров, все равные друг другу.