我的理解是“Arraylists”是对内存中某个地址的引用,因此要停止覆盖它。我们需要创建新的,这就是我所做的
所以基本上我试图从文件加载一些数据并将加载的行与现有数据进行比较,如果存在,它将被添加到“temp_super”,然后将使用“temp_super”创建一个新的“NonPlayableFighter”
我也尝试过
temp_super = new ArrayList<SuperAttack>();
出了同样的问题
ArrayList<x-men> strongFoes= new ArrayList<x-men>();
ArrayList<SuperAttack> temp_super = null;
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = "";
int position = 1;
NonPlayableFighter non;
int k=0;
while ((line = br.readLine()) != null)
{
line.replace("\\s", "");
String[] array = line.split(",");
temp_super = new ArrayList<SuperAttack>();
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < superattack.size(); j++)
{
if (array[i]
.equals(superattack.get(j).getName()))
{
temp_super.add(superattack.get(j));
break;
}
}
}
}
if(k==1)
System.out.print(strongFoes.get(0)
.getSuperAttacks().get(0).getName());
//i have checked till here and the first non is still have old data
non = new NonPlayableFighter(name, level, maxhealth,
blastdamage, physicaldamage, maxki, maxstamina,
strong, temp_super, temp_ultimate);
strongFoes.add(non);
k++
......但我得到的始终是整个“strongFoes”中的最后一个“temp_super” 就在 non = new(...) 之前,预期数据就在那里 数据被新数据替换后我不知道为什么 为什么会这样呢?
最佳答案
这里的问题是您只初始化 super_temp
ArrayList一次当position == 1
if (position == 1)
{
temp_super = new ArrayList<SuperAttack>();
temp_super.clear();
...
但是然后你通过执行 position++
来增加位置以及所有后续non = new NonPlayableFighter(...)
调用具有相同的对象 temp_super
.
关于java - arraylist不断更新其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35619558/