자바

JAVA STEP 37. HashMap 직접 구현하기

IT의 큰손 2023. 2. 24. 11:51
728x90

MyHashMap 클래스를 직접 구현

  • 조건
  • 1. 행동
    • String put(String key, String value)
      • 키와 값을 요소로 추가한다.
      • key: 추가할 요소의 키
      • value: 추가할 요소의 값
      • return: nul
    • String get(String key)
      • 키에 대응하는 요소의 값을 가져온다.
      • key: 가져올 요소의 키
      • return: 가져올 요소의 값
    • int size()
      • 요소의 개수를 반환한다.
      • return: 요소의 개수
    • String put(String key, String value)
      • 해당키의 값을 요소로 수정한다.
      • key: 수정할 요소의 키
      • value: 수정할 요소의 값
      • return: 수정하기 전 요소의 값
    • String remove(String key)
      • 원하는 키의 요소를 삭제한다.
      • key: 삭제할 요소의 키
      • return: 삭제된 요소의 값
    • boolean containKey(String key)
      • 해당 키가 존재하는지 확인한다.
      • key: 확인할 키
      • return: 키의 존재 유무
    • boolean containsValue(String value)
      • 해당 값이 존재하는지 확인한다.
      • value: 확인할 값
      • return: 값의 존재 유무
    • void clear()
      • 배열의 모든 요소를 삭제한다
    • void trimToSize()
      • 배열안의 요소의 개수만큼 배열의 길이를 줄인다.
  • 2. 소스코드
  •  
public class MyHashMap {

	private String[] keys; 
	private String[] values;
	private int index;
	
	public MyHashMap() {
		this.keys = new String[4];
		this.values = new String[4];
		this.index = 0;
	}
	public String toString() {
		String temp = "";
		
		temp += String.format("length : %d\n", this.keys.length);
		temp += String.format("index : %d\n", this.index);
		temp += String.format("\r\n");
		for(int i=0; i<this.keys.length; i++) {
			temp += String.format(" [%s] : %s\n", this.keys[i], this.values[i]);
		}
		temp += String.format("\n");
		
		return temp;
	}
	
	public String put(String key, String value) {
		
		if(getIndex(key) == -1) {
			if(checkList()) {
				doubleList();
			}
			this.keys[this.index] = key;
			this.values[this.index] = value;
			index++;
		}else {
			this.values[getIndex(key)] = value;
		}
		
		return null;
	}
	
	//index의 길이가 현재 list의 길이와 같은지 즉, 방이 꽉찼는지 검사
	public boolean checkList() {
		if(this.index == this.keys.length && this.index == this.values.length) {
			return true;
		}
		return false;
	}
		
		//배열의 길이가 꽉 찼다면, 배열의 길이를 2배로 늘려주는 연산
	public void doubleList() {
		String[] temp = new String[this.keys.length*2];
		String[] temp2 = new String[this.values.length*2];
			
		for(int i=0; i<this.keys.length; i++) {
			temp[i] = this.keys[i];
		}
		this.keys = temp;
			
		for(int i=0; i<this.values.length; i++) {
			temp2[i] = this.values[i];
		}
		this.values = temp2;
	}
	
	public String get(String key) {
		
		int index = getIndex(key);
		
		if(index != -1) {
			return this.values[index];
		}else {
			return null;
		}
	}
	
	public int getIndex(String key) {
		
		for(int i=0; i<this.index; i++) {
			if(this.keys[i].equals(key)) {
				return i;
			}
		}return -1;
	}
	
	public int size() {
		return this.index;
	}
	
	public String remove(String key) {
		int index = getIndex(key);
		String temp = "";
		temp += String.format("[%s] : %s 삭제됩니다." , this.keys[index], this.values[index]);
		
		if(index > -1) {
			for(int i=index; i<=this.keys.length-2; i++) {
				this.keys[i] = this.keys[i+1];
			}
			for(int i=index; i<this.values.length-2; i++) {
				this.values[i] = this.values[i+1];
			}
			this.index--;
		}
		return temp;
	}
	
	public boolean containsKey(String key) {
		int index = getIndex(key);
		
		if(index > -1) {
			return true;
		}else {
			return false;
		}
	}
	
	public boolean containsValue(String value) {
		
		for(int i=0; i<this.values.length; i++) {
			if(this.values[i].equals(value)) {
				return true;
			}
		} return false;
	}
	
	public void clear() {
		String [] temp = new String[4];
		
		this.keys = temp;
		this.values = temp;
		
		this.index = 0;
	}
	
	public void trimToSize() {
		String [] temp = new String[this.index];
		String [] temp2 = new String[this.index];
		
		for(int i=0; i<this.index; i++) {
			temp[i] = this.keys[i];
			temp2[i] = this.values[i];
		}
		this.keys = temp;
		this.values = temp;
	}
public class Q0107 {

	public static void main(String[] args) {
		
		//배열 생성
		MyHashMap map = new MyHashMap();

		//추가
		System.out.println("-추가-");
		map.put("국어", "합격");
		map.put("영어", "불합격");
		map.put("수학", "보류");

		//읽기
		System.out.println("-읽기-");
		System.out.println(map.get("국어"));
		System.out.println(map.get("영어"));
		System.out.println(map.get("수학"));

		//개수
		System.out.println("-개수-");
		System.out.println(map.size());

		//수정
		System.out.println("-수정-");
		map.put("영어", "합격");
		System.out.println(map.get("영어"));

		//삭제
		System.out.println("-삭제-");
		map.remove("영어");
		System.out.println(map.get("영어"));

		//검색(key)
		System.out.println("-검색(key)-");
		if (map.containsKey("국어")) {
		      System.out.println("국어 점수 있음");
		} else {
		      System.out.println("국어 점수 없음");
		}

		//검색(value)
		System.out.println("-검색(value)-");
		if (map.containsValue("합격")) {
		      System.out.println("합격 과목 있음");
		} else {
		      System.out.println("합격 과목 없음");
		}

		//초기화
		System.out.println("-초기화-");
		map.clear();
		System.out.println(map.size());
	}

}

 

  • 실행결과

MyHashMap 실행결과

 

728x90