I have a problem trying to insert a calculated result into an ArrayList of Student's list of results.
It goes like this.
I have written the code below but I'm getting multiple insertions of the same tag into FullList instead of insertion of multiple results into each tag.
Q1: I can't figure out what's wrong! Need a mind prick from the Gurus! Q2: I will be using the following code for up to 90,000 students. Is this a feasible way of housing student results?
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);
}
}
For each student in the list, you're inserting a new student if this student doesn't have the same name as the result to insert:
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);
}
}
The above should be written as:
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);
}
And the findStudentWithName method would look like this:
private Student findStudentWithName(List<Student> students, String name) {
for (Student s : students) {
if (s.getName().equalsIgnoreCase(name)) {
return s;
}
}
// no student found.
return null;
}