JAVA

[JAVA] hashMap 확장

아잠만_ 2024. 10. 5. 09:53

Map형태를 그대로 사용하고 싶을 떄

- 생성은 new를 하지않고 init()를 통해 생성 등등

package buff;

import java.util.HashMap;

import org.apache.poi.ss.formula.functions.T;

public class MapTest extends HashMap<String, Object> {
	
	public static void main(String[] args) {
		MapTest map = MapTest.init();
		map.put("key1", "value");
		map.put("key2", 1);
		map.put("key3", new StringBuffer("test"));
		String str = map.getString("key1");
		Integer intt = map.getInteger("key2");
		StringBuffer sb = map.get("key3", StringBuffer.class);
		
		System.out.println(str);
		System.out.println(intt);
		System.out.println(sb);
	}
	
	// new를 안쓰고 init함수로 생성
	// new을 안쓴다는 것은 생성자를 외부에서 못쓰게함
	// private
	private MapTest() {
		
	};
	
	private static MapTest init() {
		return new MapTest();
	}
	
	// key값을 주면 String으로 반환
	public String getString(String key) {
		Object obj = this.get(key);
		if(obj == null) {return null;}else {
			String str = String.valueOf(obj);
			return str;
		}
	}
	
	// key값을 주면 Integer로 반환, Integer는 null값이 있어 int로 반환X
	public Integer getInteger(String key) {
		Object obj = this.get(key);
		if(obj == null) {return null;}else { 
			String str = String.valueOf(obj);
			return Integer.parseInt(str);
		}
	}
	
	// 동적 반환타입 generic
	public <T> T get(String key, Class<T> gen) {
		return (T) this.get(key);
	}
}