将循环转换为哈希图打印的方法签名



我可以使用main方法中的for循环打印hashmap,但我不知道如何将其转换为hashmap打印方法。我对方法签名和将其适当地合并到for循环中感到困惑。

//Add Student object to hashmap 
HashMap<Integer, Student> s= new HashMap<Integer, Student>();
s.put(1,student1);
s.put(2,student2);
s.put(3,student3);
s.put(4,student4);
s.put(5,student5);

//For loop printer for hashmap
System.out.println();
for (HashMap.Entry<Integer, Student> m : s.entrySet()){
System.out.println(m.getValue());
System.out.println();
}
// Print method for hashmap
private static void printingMap(HashMap.Entry<Integer, Student> s){
for (HashMap.Entry<Integer, Student> m : s.entrySet()){
System.out.println(m.getValue());
System.out.println();
}
}

因为printMap的方法应该采用Map(而不是单个Map.Entry(。比如

private static void printingMap(Map<Integer, Student> s){
for (Map.Entry<Integer, Student> m : s.entrySet()){
System.out.println(m.getValue());
System.out.println();
}
}

然后

printingMap(s);

调用它。不要忘记覆盖Student中的toString

最新更新