【发布时间】:2017-10-05 00:01:53
【问题描述】:
我在调试代码时遇到一个问题,我注意到我的对象列表数组在将新对象添加到列表数组之前替换了一个对象
以往的研究
我研究了一些类似的情况,这种情况不适用于我的情况。 Why can't I add objects to my List<>?
// 我想我会检查一下我的列表是否因为我编码的东西而没有添加。然而,情况似乎并非如此
这是一篇有点帮助的帖子,但是我的 add student 调用在请求新对象时已经有了 new 关键字。
相关对象列表代码
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;
}
相关对象代码
public MyStudent(String inID, String inLastName, String inFirstName,int inTotalCredits, double inTotalGradePoints)
{
ID = inID;
firstName = inFirstName;
lastName = inLastName;
totalCredits = inTotalCredits;
totalGradePoints = inTotalGradePoints;
}
从 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));
当新学生替换旧实例变量时,它会替换我的 MuStudentList 中的引用。在我调用原始 num 递增并添加到 objectlist 之前我做错了什么?
简而言之,当我用新值替换引用的值时,我试图将一个学生(对象)添加到我的数组列表中。它还替换了 myStudentlist 中引用的值(这是否意味着一旦对象命中列表,我就无法取消引用该对象?)
当我在到达 find 函数之前调用 myStudent 的构造函数时会出现问题。然而,由于 == 不应该与字符串一起使用,我接受了其他程序员的建议并对其进行了更新。
【问题讨论】:
-
检查 getId () 比较,这些是字符串,它正在使用 ==
标签: java object arraylist constructor