事件起因就是,我在写一个程序的时候用到了arrayList,然后需求就是用其添加一个一个对象。没错就是你想的那样,里面每一个数据都是相同的, 本来这次错误是不应该犯的,但是因为工作的关系,好久没写java代码了。我大意了,没有闪。
原因
1 |
public static ArrayList<Result> resultArrayList = new ArrayList<>(); |
主要就是这个list,因为我需要循环存储每一个对象,那么思路就是用一个临时对象,赋值后,再将其存储到list中。其实,这种在for循环中是正常的,因为每一次遍历都会重新new出一个临时对象,但是我的需求有点不一样,我的需求是for循环中,隔几次存储一次。
改进
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
public static void GetContent(File file){ String[] str = null; String[] content = null; int[] grade = new int[4];//分数 if(file.exists()){ try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line = ""; int i =0;//五次一轮回 Question question = null; while ((line = br.readLine()) != null) { //按行读取文件流的内容 if (i == 0) { question = new Question(); question.setQuestion(line); // questions[qn].setQuestion(line); } else if (i == 1) { str = new String[100]; content = new String[4]; str = line.split(","); content[i - 1] = str[0]; grade[i - 1] = Integer.parseInt(str[1]); } else if (i == 2) { str = line.split(","); content[i - 1] = str[0]; grade[i - 1] = Integer.parseInt(str[1]); } else if (i == 3) { str = line.split(","); content[i - 1] = str[0]; grade[i - 1] = Integer.parseInt(str[1]); } else if (i == 4) { str = line.split(","); content[i - 1] = str[0]; grade[i - 1] = Integer.parseInt(str[1]); // questions[qn].setContent(content); // questions[qn].setGrade(grade); question.setContent(content); question.setGrade(grade); questionArrayList.add(question); qn++; i = -1; } i++; } fr.close(); br.close(); } catch (Exception e) { e.printStackTrace(); } }else{ System.out.println("文件不存在"); } } |
有一种很好解决的方法就是你提前做好声音,然后在循环里面,第一次声明需要的时候,你就把他new出来,在什么地方收尾放入list的时候,你就直接放进去。