I am having a problem where when I'm debugging my code I notice that my object list array is replacing an object before a new object is added to the list array
Previous Research
I looked researched some similar situations this situation did not apply to my case. Why can't I add objects to my List<>?
// thought I would check an see if my list was not adding because of something I coded. However, this did not seem to be the situation
This was a somewhat helpful post however my add student call already has the new keyword when asking for a new object.
Relevant Object list Code
private MyStudent[] list;
private int num = 0;
private static final int GROW_BY = 2;
public MyStudentList()
{
list = new MyStudent[GROW_BY];
num = 0;
}
public boolean add(MyStudent inStudent)
{
int index = find(inStudent);
if (index == -1)
{
list[num++] = inStudent;
return true;
}
else
return false;
}
private int find(MyStudent inStudent)
{
int index = -1;
int test = 0;
for (int i = 0; i < list.length && index == -1; i++)
{
if(list[i] == null)
{
return index;
}
if (inStudent.getID().equals(list[i].getID()))
{
index = i;
}
}
return index;
}
Relevent object code
public MyStudent(String inID, String inLastName, String inFirstName,int inTotalCredits, double inTotalGradePoints)
{
ID = inID;
firstName = inFirstName;
lastName = inLastName;
totalCredits = inTotalCredits;
totalGradePoints = inTotalGradePoints;
}
call from main
MyStudent addStudent = new MyStudent("833006711", "James", "Butt", 106, 202);
System.out.println(myList.add(addStudent)); // add the student
myList.print();
System.out.println(myList.add(addStudent));//student exists return false
myList.print();
addStudent = new MyStudent("261458460", "Josephine", "Darakjy", 37, 91.33); // here is where my code faults
System.out.println(myList.add(addStudent));
When the new student replaces the old instance variable it replaces the reference in my MuStudentList. before i call the primative num to increment and add to objectlist What am i doing wrong?
in short i am trying to add a student(object) to my arraylist however, when i replace the referenced values with new values. it also replaces the values referenced in myStudentlist ( does this mean that i cannot dereference the object once it hits the list?)
The problem occurs when i call the constructor for the myStudent before i reach the find function. However since == shouldnt be used with strings i took the advice of fellow programmers and updated that as well.