我在尝试将计算结果插入Student的结果列表的ArrayList时遇到问题。
就是这样。
我已经编写了下面的代码但是我在同一个标签中多次插入FullList而不是在每个标记中插入多个结果。
Q1:我无法弄清楚出了什么问题!需要大师的精神刺激! Q2:我将为多达90,000名学生使用以下代码。这是否是容纳学生成绩的可行方式?
class Result {
String name;
int result;
public Result(String name, int result) {
this.name = name;
this.result = result;
}
/* start - Getting hungup over this method
* Something is wrong here and i don't know what it is
*/
public void setResult(ArrayList <Student> fullList) {
for (Student s : fullList) {
if (s.getName().equalsIgnoreCase(this.name)) {
s.setResult(this);
}
else { /* enters here if Student does not exist in fullList */
Student s = new Student(this.name); /* create new student */
s.setResult(this); /* insert result into Student's resultslist */
fullList.add(s); /* add Student into fullList */
}
}
}
/* end */
public String getName() {
return this.name;
}
}
class Student {
String name;
ArrayList <Result> resultslist;
public Student(String name) {
this.name = name;
resultslist = new ArrayList <Result> ();
}
public void setResult(Result result) {
this.resultslist.add(result);
}
public String getName() {
return this.name;
}
}
class StudentResults {
public static void main (String [] args) {
ArrayList <Student> FullList = new ArrayList <Student> ();
Result r1 = new Result("John", 12);
Result r2 = new Result("Jamie", 99);
Result r3 = new Result("John", 69);
Result r4 = new Result("Jacque", 56);
Result r5 = new Result("Jacque", 100);
Result r6 = new Result("Jamie", 100);
r1.setResult(FullList);
r2.setResult(FullList);
r3.setResult(FullList);
r4.setResult(FullList);
r5.setResult(FullList);
r6.setResult(FullList);
}
}
答案 0 :(得分:2)
对于列表中的每个学生,如果此学生的名称与插入的结果不同,则您将插入新学生:
for (Student s : fullList) {
if (s.getName().equalsIgnoreCase(this.name)) { // current student has same name as result
s.setResult(this);
}
else { // current student doesn't have the same name as result
Student s = new Student(this.name);
s.setResult(this);
fullList.add(s);
}
}
以上内容应写为:
Student s = findStudentWithName(fullList, this.name);
if (s == null) {
Student s = new Student(this.name);
s.setResult(this);
fullList.add(s);
}
else {
s.setResult(this);
}
findStudentWithName方法如下所示:
private Student findStudentWithName(List<Student> students, String name) {
for (Student s : students) {
if (s.getName().equalsIgnoreCase(name)) {
return s;
}
}
// no student found.
return null;
}
答案 1 :(得分:2)
使用Map/HashMap
代替List:
Map<String, Student> fullStudents= new HashMap<Student>();
并将其用作:
public void setResult(Map<String, Student> fullMap) {
Student s = fullMap.get(this.name.toLowerCase());
if(s == null){
s = new Student(this.name);
fullMap.put(this.name.toLowerCase(), s);
}
s.setResult(this);
}
它更简单,更清洁。
要随时获取学生列表,您只需:
List<Student> fullList = fullMap.values();