簡體   English   中英

從Java中的HashMap檢索對象?

[英]Retrieving objects from HashMap in Java?

我有一個HashMap,其中將studentIds作為鍵,將Student對象作為值,

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());

您只需要為輸入使用參數化類型:

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

(請注意,一個類不可能有一個名為“ int”的字段,因為這是一個語言關鍵字)。

只需在Student中實現toString ,您發布的代碼將按原樣工作:

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

您可以通過以下方式實現。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM