Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中从HashMap检索对象?_Java - Fatal编程技术网

在Java中从HashMap检索对象?

在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,它将studentID作为键,将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;
       }

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

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