본문 바로가기
주식/기타

자바 static Map 사용과 초기화

by heavenLake 2022. 2. 17.
반응형

 

 

출처사이트 : https://trudger.tistory.com/m/entry/static-map-%EC%82%AC%EC%9A%A9-%EA%B4%80%EB%A0%A8static-field-initialzation

 

 

맵핑정보를 static map 에 선언해 놓고 쓰고 싶다.

우선 static field를 선언했다.

 
public class Test{
    static private final Map<String, String> mappingFileds = new HashMap<String, String>();
}

초기화를 어떻게 할까??

구글링 하니 몇가지 방법이 나왔다.

1.  static initializer block

 private static final Map<Integer, String> myMap;
    static {
        Map<Integer, String> aMap = ....;
        aMap.put(1, "one");
        aMap.put(2, "two");
        myMap = Collections.unmodifiableMap(aMap);
    }

참고로 class block(instance block 이라고도 하던데..) 안에 brace로{}감싼 부분을 initialzer block이라고 하고
나중에 컴파일러는 이부분을 constructor에 복사해준다고 한다.
물론 static을 붙여주면 한번만 실행.

2. static method

private static final Map<Integer, String> MY_MAP = createMap();

    private static Map<Integer, String> createMap() {
        Map<Integer, String> result = new HashMap<Integer, String>();
        result.put(1, "one");
        result.put(2, "two");
        return Collections.unmodifiableMap(result);
    }
3. double brace initialization (anonymous class 이용한 trick)
private static final Map<Integer, String> CONSTANT_MAP = 
    Collections.unmodifiableMap(new HashMap<Integer, String>() {{ 
        put(1, "one");
        put(2, "two");
    }});

 

 

* ImmutableMap 사용하면 바로 값을 넣어줄 수도 있다

static final Map<Integer, String> MY_MAP = ImmutableMap.<Integer, String>builder()
    .put(1, "one")
    .put(2, "two")
    // ... 
    .put(15, "fifteen")
    .build();

 

ref    

http://stackoverflow.com/questions/507602/how-to-initialise-a-static-map-in-java

반응형

댓글