public class CHashMap {
static HashMap<Integer, Student> student = new HashMap<Integer, Student>();
public static void main(String[] args) {
student.put (1111, new Student ("Kim Ye-si", "3rd grade", "English"));
student.put (2222, new Student ("Advanced Example", "Grade 1", "English"));
student.put (3333, new Student ("Kim Ye-si", "Second Grade", "Com Engineering"));
student.put (4444, new Student ("this example", "grade 4", "Chinese literature"));
student.put (5555, new Student ("literary example", "fourth grade", "medical course"));
printKey();
}
static public void printKey() {
System.out.println("this is key----------");
for(int key : student.keySet()) {
System.out.println(key);
}
}
}
The above results are printed in the order 5555 - 3333 - 1111 - 4444 - 2222.
Shouldn't it be printed in the order of putting it in?
hashmap java
According to the HashMap API document, HashMap does not guarantee the order of the maps.
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
However, you can use the LinkedHashMap class to perform repeat statements in the order in which they are inserted.
This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html
© 2024 OneMinuteCode. All rights reserved.