我在向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>();
}
答案 0 :(得分:4)
每次迭代都会创建一个新的obj
,因此您添加的字符串将丢失。尝试在循环之前移动obj = new Save();
。
答案 1 :(得分:3)
for(int i = 0; i < number;i++) {
obj = new Save();
每次循环重新开始时, obj
被实例化为新的Save
。这意味着您前一个循环的所有进度都将丢失,新的Save
是接收插入的进度。你只想在循环之前的某个地方创建一次obj
。交换行的顺序应该使程序工作。
obj = new Save();
for(int i = 0; i < number;i++) {