Java의 HashMap에서 출력결과가 왜 이렇게 나오는 걸까요?
조회수 2200회
public class CHashMap {
static HashMap<Integer, Student> student = new HashMap<Integer, Student>();
public static void main(String[] args) {
student.put(1111, new Student("김예시", "3학년", "영문과"));
student.put(2222, new Student("정예시", "1학년", "영문과"));
student.put(3333, new Student("김예시", "2학년", "컴공과"));
student.put(4444, new Student("이예시", "4학년", "중문과"));
student.put(5555, new Student("문예시", "4학년", "의예과"));
printKey();
}
static public void printKey() {
System.out.println("this is key----------");
for(int key : student.keySet()) {
System.out.println(key);
}
}
}
위의 결과가 5555 - 3333 - 1111 - 4444 - 2222 순서로 출력이 됩니다.
넣을 때의 순서대로 출력이 되야 하는게 아닌가요?
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
HashMap API 문서에 따르면, HashMap은 해당 map의 순서를 보장하지 않는다고 명시되어 있습니다.
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
하지만, LinkedHashMap 클래스를 사용하면 삽입된 순서대로 반복문을 수행하도록 할 수 있습니다.
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
-
(•́ ✖ •̀)
알 수 없는 사용자
-
댓글 입력