首页 > 解决方案 > 为什么我的数组列表的 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”。我一直在寻找堆栈溢出,但找不到解决方案。

这是运行代码后的调试器: 在此处输入图像描述

标签: javaarraylist

解决方案


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?


推荐阅读