I am writing a program in Java which is supposed to be like a student administration with different lists of students, subjects, teachers and so on. The program shall among others include one general subjectlist and one subjectlist for each student. The problem is that when I create two different subjects and add it to the general subjectlist and later on find one of these and add it to the student subjectlist, the student subjectlist contains both of these subjects.
I have searched the web but it is not so easy to know what to look for!
I am writing the datastructure myself.
My code looks something like this:
public class Subject() {
Subject next;
//constructor with parameters
}
public class Subjectlist() {
private Subject first;
//methods for adding to list, deleting, find and so on
}
public class Participation {
Subjectlist subjects;
public Participation() {
subjects = new Subjectlist();
}
}
public class Student() {
Participation participation;
public Student(paramters) {
participation = new Participation();
}
public class mainclass() {
public static void main(String [] args) {
Subjectlist subjectlist = new Subjectlist();
Studentlist students = new Studentlist();
Student student = new Student(parameters);
students.addToList(student);
Subject subject1 = new Subject(parameters);
Subject subject2 = new Subject(parameters);
subjectlist.addToList(subject1);
subjectlist.addToList(subject2);
Subject subject = subjectlist.find(subjectid); //Finds the subject with an ID given in the constructor
student.participation.subjects.addToList(subject);
//Now student.participation.subjects contains both subject1 and subject2
}
}
Any help would be much appreciated!
EDIT:
This is the find and addToList methods:
public String addToList(Subject new) {
Subject pointer = first; //Subject first is declared in the class
if(new == null) {
return "The subject was not added.";
}
else if (first == null) {
first = new;
return "The subject was added";
}
else {
while ( pointer.next != null )
pointer = pointer.next;
pointer.next = new;
return "The subject was added";
}
}
public Subject find(String subjectid) {
Subject found = null;
Subject pointer = first;
while (pointer != null) {
if (pointer.getSubjectID().equals(subjectid)) {
found = pointer;
}
pointer = pointer.next;
}
return found;
}
List<Subject>anywhere... I would expect to see such a construct. But maybe you should reduce the problem to a shorter version and post then the full code of this condensed problem.