Java 用于hashmap打印的循环到方法签名的转换
我能够在main方法中使用for循环打印hashmap,但我不知道如何将其转换为hashmap打印方法。我对方法签名和将其适当地合并到for循环中感到困惑Java 用于hashmap打印的循环到方法签名的转换,java,methods,printing,hashmap,Java,Methods,Printing,Hashmap,我能够在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,studen
//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();
}
}
//将学生对象添加到hashmap
HashMap s=新的HashMap();
s、 put(1,学生1);
s、 put(2,学生2);
s、 put(3,学生3);
s、 put(4,学生4);
s、 put(5,学生5);
//用于hashmap的循环打印机
System.out.println();
对于(HashMap.Entry m:s.entrySet()){
System.out.println(m.getValue());
System.out.println();
}
//hashmap的打印方法
私有静态void printingMap(HashMap.Entry s){
对于(HashMap.Entry m:s.entrySet()){
System.out.println(m.getValue());
System.out.println();
}
}
因为printMap
的方法应该采用Map
(而不是单个Map.Entry
)。像
叫它。不要忘了在Student
中覆盖toString
,这是可行的。我花了几个小时讨论不同的例子,什么都没有。我只是有点理解代码里发生了什么。
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);