java - 为什么我的数组列表的 Java Set 方法不起作用?
问题描述
public class Student implements Comparable<Student>
{
private String name;
private double gradePoints = 0;
private int units = 0;
private int index=-1;
public Student(String name)
{
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int i) {
index=i;
}
public Student(String name, double gpa, int units)
{
this.name = name;
this.units = units;
this.gradePoints = gpa * units;
}
public String getName()
{
return name;
}
public double gpa()
{
if(units > 0)
return gradePoints/units;
return 0;
}
public void addGrade(double gradePointsPerUnit, int units)
{
this.units += units;
this.gradePoints += gradePointsPerUnit * units;
}
public int compareTo(Student other) //Do not change this method. Ask me why if you like.
{
double difference = gpa() - other.gpa();
if(difference == 0) return 0;
if(difference > 0) return 14; //Do not hardcode 14, or -12, into your code.
return -12;
}
}
import java.util.ArrayList;
public class heapgang {
public static void main(String[] args) {
ArrayList<Student> x= new ArrayList<Student>();
Student a= new Student("bob",1,2);
Student b= new Student("arav",3,4);
x.add(a);
x.add(b);
x.set(0, b); // should change the first element in the arraylist to student named "arav"
}
}
在我的代码末尾,第一个元素没有更改为名为 arav。为什么?我认为在 set 方法之后,arraylist 中的两个元素都将被命名为“arav”。我一直在寻找堆栈溢出,但找不到解决方案。
解决方案
Something smells about that debugger output - it says you have the same Student object (id=48) in the list twice (as you expect) but the contents are different. Maybe the debugger hasn't entirely refreshed its display?
What happens if you loop through the contents of the list printing out the students' names?
推荐阅读
- javascript - 电子表格中的数据未填充到电子邮件正文中
- python-3.x - Youtube_DL Python 实现类型错误的 Youtube 提取器:add_cookie_header() 缺少 1 个必需的位置参数:“请求”
- json - (Swift)如何解析有时包含某个字段的 JSON 响应?
- c - 从开关引脚 Tiva c Launchpad 读取数据
- python - Pylint 不理解 if/else 语句?
- docker - 如何获取在 docker 映像中定义的入口点以将其包装在 helm 安装中
- hibernate-search - Hibernate Search 6.0.2.Final 与 opendistro
- macos - 如何在 macOS 上获取屏幕时间数据?
- python - 仅当消息从 certin 客户端发送时如何批准消息(具有线程的 Python 多客户端套接字服务器)
- python - 如何使用 Python 检查多个值是否包含 CSV 数据集?