[JAVA] LinkedHashMap을 사용하는 방법

Yuri Lee·2023년 5월 16일
0

JAVA

목록 보기
3/11

LinkedHashMap이란?

Map 인터페이스를 구현한 클래스이며 Linked List 이면서 Hash table이다.

특징

  • 입력했던 순서대로 Entry가 LinkedHashMap에 mapping 된다.
  • LinkedHashMap은 double-linked List로 모든 Entry를 유지한다.
  • key, value에 null 입력이 가능하다.
  • get, put, remove, containsKey 메소드를 호출할때 O(1)의 시간복잡도를 갖는다.

생성자

LinkedHashMap<String, Integer> map4 = new LinkedHashMap<String, Integer>(10, 0.75f, true);

LinkedHashMap은 생성자로 initial capacity, load factor, accessOrder를 매개변수로 객체를 생성할 수 있다.

1) accessOrder가 true인 경우

LinkedHashMap<String, Integer> map1 = new LinkedHashMap<String, Integer>(16, 0.75f, true);

map1.put("first", 2);
map1.put("second", 3);
map1.put("third", 4);
map1.put("fourth", 5);

map1.get("first");
map1.get("third");

map1.forEach((key, value)->{
	System.out.println("Key:"+key+", Value:"+value);
    });
Key:second, Value:3
Key:fourth, Value:5
Key:first, Value:2
Key:third, Value:4

2) accessOrder : false일 경우

LinkedHashMap<String, Integer> map2 =LinkHashMap<String, Integer>(16, 0.75f, false);

map2.put("first", 2);
map2.put("second", 3);
map2.put("third", 4);
map2.put("fourth", 5);

map2.get("first");
map2.get("third");

map1.forEach((key, value) -> {
	System.out.println("Key:" + key + ", Value:" + value);
});
Key:first, Value:2
Key:second, Value:3
Key:third, Value:4
Key:fourth, Value:5

accessOrder라는 Entry에 access하는 mode를 나타낸다.
true일 경우 입력된 순서 중에 access 빈도 낮은 것부터 접근하낟.
false일 경우 입력된 순서로 Entry에 접근한다.
map1의 경우 accessOrder를 true로 지정하고 생성했다.
get메소드에 first, third를 access하고 나면 first, third는 access 빈도가 1이고, second, fourth의 경우 access 빈도가 0이다.
그래서 forEach()메소드를 통해 결과를 출력하면 빈도수가 낮은 순부터 출력된다.

메소드

  • clear() 반환형:void
    LinkedHashMap 객체의 모든 mapping을 삭제
  • containsValue(Object value) 반환형:boolean
    매개변수로 입력된 value값이 LinkedHashMap 객체에 존재한다면 true, 없으면 false를 반환한다.
  • entrySet() 반환형:Set<Map.Entry<K,V>>
map1.put("a", 1);

map1.put("b", 2);
map1.put("c", 3);
map1.put("d", 4);

//Set<Map.Entry<String, Integer>> 객체를 얻는 메소드
Set<Map.Entry<String, Integer>> set = map1.entrySet();
Iterator it = set.iterator();

while(it.hasNext()){
  Object obj = it.next();
  System.out.println(obj);
}

System.out.println();

for(Map.Entry<String, Integer> entry : map1.entrySet()){
  String key = entry.getKey();
  Integer value = entry.getValue();
  System.out.println(key + " " + value);
}

-> 결과값


Set<Map.Entry<K,V>>의 객체를 반환하는 메소드이며 사용법은 위의 코드와 같습니다.

테스트해보니 Set<Map.Entry<K,V>> set의 Iterator의 generic을 사용할 경우 컴파일 에러가 납니다.

그래서 generic을 지정하지 않고 Iterator 객체를 얻어와서 while문 안에서 set의 객체를 하나씩 확인해보니

a=1의 형태로 출력이 됩니다.

그리고 아래의 for문은 entrySet()의 메소드를 사용한 다른 예시입니다.

이 때는 entry 객체에서 getKey()메소드를 호출하여 key값, getValue()메소드를 호출하여 value값을 얻어올 수 있습니다.

  • get(Object key) 반환형:K
    LinkedHashMap 객체에 key에 해당하는 value가 있으면 그 값을 반환, 없으면 null을 반환한다.

  • getOrDefault(Object key, V defalutValue) 반환형:V
    LinkedHashMap 객체에 key에 해당하는 value값이 있다면 그 값을 반환하고, 없으면 매개변수로 입력된 defaultValue 값을 반환한다.

  • keySet() 반환형:Set
    LinkedHashMap 객체에 모든 key값을 가진 Set객체를 반환한다.

등등..

REFERENCES

https://developer-syubrofo.tistory.com/13
https://developer-syubrofo.tistory.com/7

profile
개발자 이유리

0개의 댓글