【问题标题】:Retrieving objects from HashMap in Java?从 Java 中的 HashMap 中检索对象?
【发布时间】:2012-05-06 11:04:08
【问题描述】:

我有一个 HashMap,它将 studentIds 作为键,将学生对象作为值,

HashMap<Integer, Student> hashMap = hashTables.buildHash(students);

public static HashMap<Integer, Student> buildHash(Student[] students) {
            HashMap<Integer, Student> hashMap = new HashMap<Integer, Student>();
            for (Student s : students) hashMap.put(s.getId(), s);
            return hashMap;
       }

下面的代码获取每个 KeyValue 对并且 s.getValue() 返回一个由 id 和字符串名称组成的学生对象,我如何检索/打印这些值(student.int、student.name);

for(Map.Entry s : hashMap.entrySet())
    System.out.print(s.getKey()+" "+s.getValue());

【问题讨论】:

    标签: java


    【解决方案1】:

    只需在 Student 中实现 toString,您发布的代码将按原样工作:

    public class Student {
        ...
        public String toString() {
          return "ID = " + this.id + ", name = " + this.name;
        }
    }
    

    【讨论】:

    • 有没有我可以检索对象的 int 和 string 值?
    • 查看 Michael Borgwardt 对此的回答,他已经涵盖了。关键是在Map.Entry 的声明中使用类型参数。那你就可以随意写e.getValue().getId()了。
    【解决方案2】:

    您只需要为条目使用参数化类型:

    for(Map.Entry<Integer, Student> s : hashMap.entrySet())
        System.out.print(s.getKey()+" "+s.getValue().getId()+" "+s.getValue().getName());
    

    (请注意,类不可能有一个名为“int”的字段,因为那是语言关键字)。

    【讨论】:

    • @Marko Topolnik:只是因为我使用了 OP 的语法违规信息来了解他的班级结构
    • 当然,我意识到它幽默的一面。只是帮助比嘲笑更好:) 请注意,在HashMap 人口代码中他使用了一个吸气剂,所以他的idname 可能是私有的,因为它们应该是。
    【解决方案3】:

    你可以通过..来实现这一点。

    for(Map.Entry<Integer, Student> s : hashMap.entrySet()){
        System.out.print(Long.valueof(s.getKey())+""+String.valueof(s.getValue().getName()));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多