gpt4 book ai didi

java - 将字符串添加到数组列表

转载 作者:行者123 更新时间:2023-12-01 07:18:47 25 4
gpt4 key购买 nike

我在将字符串添加到 ArrayList 时遇到问题。我的目标是使用 for 循环创建数组列表。但是每次循环时,它似乎总是删除以前的数据,然后用新数据替换它,因此 ArrayList 的值只有 1 而不是 4。这是完整的代码

public class SerialDemo {

private static File f;
private static Save obj1;
private static Save obj;

private static int number = 4;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//getData("newFile.txt");
for(int i = 0; i < number;i++) {
obj = new Save();
obj.arrayLocationX.add(String.valueOf(10 * i));
obj.arrayLocationY.add(String.valueOf(20 * i));
obj.arrayTitle.add(String.valueOf(30 * i));
obj.arrayDescription.add(String.valueOf(40 * i));
obj.arrayNumber.add(""+i);
}

for(String x:obj.arrayLocationX) {
System.out.println(obj.arrayLocationX);
}

//setData("newFile.txt");
/*getData("newFile.txt");

for(int i = 0; i < obj.arrayLocationX.size(); i++) {
System.out.println("Value of Desc"+obj1.arrayNumber);
System.out.println("Value of locX"+obj1.arrayLocationX.get(i));
System.out.println("Value of locY"+obj1.arrayLocationY.get(i));
System.out.println("Value of Tit"+obj1.arrayTitle.get(i));
System.out.println("Value of Desc"+obj1.arrayDescription.get(i));
System.out.println(" ");
System.out.println(obj.arrayDescription.size());
}*/
}catch(Exception e) {

}

}

private static void setData(String fileName) {
// set the object or data
try {
f = new File(fileName);
FileOutputStream fps;
fps = new FileOutputStream(f);
ObjectOutputStream dos = new ObjectOutputStream(fps);
dos.writeObject(obj);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e) {

}
}
private static void getData(String fileName) {
// get the object or data
try {
f = new File(fileName);
FileInputStream fin = new FileInputStream(f);
ObjectInputStream Oin = new ObjectInputStream(fin);
obj1 = (Save) Oin.readObject();
}catch(FileNotFoundException e) {

}catch(IOException e) {

}catch(ClassNotFoundException e) {

}
}

}

class Save implements Serializable {
ArrayList<String> arrayNumber = new ArrayList<String>();
ArrayList<String> arrayLocationX = new ArrayList<String>();
ArrayList<String> arrayLocationY = new ArrayList<String>();
ArrayList<String> arrayTitle = new ArrayList<String>();
ArrayList<String> arrayDescription = new ArrayList<String>();
}

最佳答案

每次迭代都会创建一个新的obj,因此您添加的字符串会丢失。尝试将 obj = new Save(); 移到循环之前。

关于java - 将字符串添加到数组列表<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47949326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com