【问题标题】:Getting object hash code instead of object value in ArrayList在 ArrayList 中获取对象哈希码而不是对象值
【发布时间】:2020-12-12 12:30:48
【问题描述】:

我有一个包含少量对象的“学生”ArrayList,我想将我的学生 ArrayList 转换为字符串 ArrayList,但我没有在字符串 ArrayList 中获取学生对象值,而是得到了像“Student@6acbcfc0”这样的学生对象哈希码。我在教室里有一个 toString() 方法。忽略其他类型的错误。任何形式的帮助表示赞赏。提前致谢。

public class Classroom{

    List<Student> participants=new ArrayList<Student>();

    @Override
    public String toString() {

        String results = "";

        for(Student d : participants) {

            results += d.toString(); 
    }
    return results;
  }

public String getParticipantsEmail(){
        
        ArrayList<String> str = new ArrayList<String>();

        for (int i = 0; i < participants.size(); i++) {

            str.add(participants.get(i).toString());
            
            System.out.println(str.get(i));
        }

【问题讨论】:

  • 在你的 Student 类中定义一个 toString() 方法。

标签: java arraylist hashcode


【解决方案1】:

我没有看到 Student.toString() 的实现。你有吗?

participants.get(i).toString() 调用 Student.toString(),而不是 Classroom.toString()

【讨论】:

    【解决方案2】:

    在你的 Student 类中添加一个 toString() 方法

    然后简单地调用

    System.out.println(student.get(i).toString());
    

    【讨论】:

      猜你喜欢
      • 2014-05-30
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多