HashMap은 입력된 데이터를 출력할 때 key값을 가지고 출력하기 때문에 출력하는 순서가 정해져 있지 않으나,

LinkedHashMap은 입력한 순서대로 데이터가 쌓여 있는 것을 확인할 수 있는 객체이다. 또한 HashMap의 장점을 그대로 가지고 있다.


Iterator로 출력시에도 HashMap은 순서가 없으나 LinkedHashMap은 입력된 순서에 맞게 값을 출력한다.

동일한 key의 중복을 막아주고, 특정 key의 값을 찾고자 할 떄 for문을 들어 전체 값을 검색할 필요가 없다.


순서대로 입력되어 있기 때문에, 전체 값을 순서대로 operation 해야할 때 유용하다.

HashMap 클래스를 상속 받아 만들어져 있고, Iterator를 사용하여 가져오더라도 입력시의 순서에 맞게 값을 가져올 수 있다.

LinkedList로 저장되며, HashMap과 마찬가지로 다중스레드를 사용시 Synchronized가 되지 않는다.


JDK 1.4 이상부터 사용 가능한 Collection 객체이다.


* removeEldestEntry() : put() 할 때 불리는 메소드. 들어온 순서를 기억하고 가장 오래된 값을 그 자리에 방금 들어온 값으로 대체하는 메소드.



2. 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
 
public class LinkedHashMapExample {
    public static void initData(Map<StringString> map) {
        map.put("key1""1");
        map.put("key2""2");
        map.put("key3""3");
        map.put("key4""4");
        map.put("key5""5");
        map.put("key6""6");
        map.put("key7""7");
        map.put("key8""8");
        map.put("key9""9");
        map.put("key10""10");
    }
    
    public static void printResult(Map<StringString> map) {
        Set<String> set = map.keySet();
        Iterator<String> iter = set.iterator();
        
        while (iter.hasNext()) {
            String key = ((String)iter.next());
            String value = map.get(key);
            
            System.out.println("key : " + key + ", value : " + value);
        }
    }
    
    public static void main(String[] args) {
        System.out.println("==========HashMap Test=========");
        
        Map<StringString> hashMap = new HashMap<StringString>();
        
        initData(hashMap);
        
        printResult(hashMap);
        
        System.out.println("==========LinkedHashMap Test=====");
        
        Map<StringString> linkedHashMap = new LinkedHashMap<StringString>();
        
        initData(linkedHashMap);
        
        printResult(linkedHashMap);
    }
}
cs


+ Recent posts