在Java中从HashMap检索对象?
我有一个HashMap,它将studentID作为键,将student对象作为值在Java中从HashMap检索对象?,java,Java,我有一个HashMap,它将studentID作为键,将student对象作为值 HashMap<Integer, Student> hashMap = hashTables.buildHash(students); public static HashMap<Integer, Student> buildHash(Student[] students) { HashMap<Integer, Student> hashMap = ne
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;
}
您只需对条目使用参数化类型:
for(Map.Entry<Integer, Student> s : hashMap.entrySet())
System.out.print(s.getKey()+" "+s.getValue().getId()+" "+s.getValue().getName());
for(Map.Entry 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()));
}
for(Map.Entry s:hashMap.entrySet()){
System.out.print(Long.valueof(s.getKey())+“”+String.valueof(s.getValue().getName());
}
我是否可以检索对象的int和string值?请参阅Michael Borgwardt的答案,他已经介绍过了。关键是要在映射项的声明中使用类型参数。然后你可以自由地写e.getValue().getId()
@Marko Topolnik:只是因为我使用了OP的语法违反了关于他的类结构的信息,当然,我意识到了它的幽默性。只是帮助比模仿更好:)还要注意,在HashMap
总体代码中,他使用了一个getter,因此他的id
和name
可能是私有的,因为它们应该是私有的。
for(Map.Entry<Integer, Student> s : hashMap.entrySet()){
System.out.print(Long.valueof(s.getKey())+""+String.valueof(s.getValue().getName()));
}