【发布时间】:2022-07-27 23:46:23
【问题描述】:
我有一个单元格数组。 public static Cell[][] island = new Cell[3][3];
每个单元格都有 x 和 y 坐标以及“居住”在单元格内的动物列表。我需要用列表中的随机动物随机填充这个数组。 public static List<Alive> allanimals = new ArrayList<>();
这就是我对列表进行编码和“填充”的方式。
public static void generateIsland() {
for (int i = 0; i < 10; i++) {
int random = (int) (Math.random() * 100);
if (random < 50) {
allanimals.add(new Bear(500,5,0,0));
} else {
allanimals.add(new Sheep(70,0,0));
}
}
System.out.println("Randomly create all animals list" + allanimals);
int initialcount = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
try {
int randomdata = r.nextInt(0, allanimals.size() );
List<Alive> animalsInCell = new ArrayList<>();
animalsInCell = allanimals.subList(initialcount, initialcount + randomdata);
initialcount += randomdata;
island[i][j] = new Cell(i, j, animalsInCell);
} catch (Exception e) {
island[i][j] = new Cell(i, j, new ArrayList<Alive>());
}
}
}
}
最后我有一些空单元格,我相信这部分animalsInCell = allanimals.subList(initialcount, initialcount + randomdata); 可以做得更优雅。如何用 allanimals 列表中的元素填充我的 Island 数组?
这是我的 Cell 课
@Data
@AllArgsConstructor
public class Cell extends Thread{
private int x;
private int y;
public List<Alive> animals;
//method run()}
【问题讨论】:
标签: java