JAVA

HashMap 구현

웹개발자준비 2018. 7. 31. 14:05

public class HashMap {


public static void main(String[] args) {

//HashMap.java

//배열 생성

MyHashMap map = new MyHashMap();

//추가

map.put("국어", "합격");

map.put("영어", "불합격");

map.put("수학", "보류");

//읽기

System.out.println(map.get("국어"));

System.out.println(map.get("영어"));

System.out.println(map.get("수학"));

//개수

System.out.println(map.size());

//수정

map.put("영어", "합격");

System.out.println(map.get("영어"));

//삭제

map.remove("영어");

System.out.println(map.get("영어"));

//검색(key)

if (map.containKey("국어")) {

    System.out.println("국어 점수 있음");

} else {

    System.out.println("국어 점수 없음");

}


//검색(value)

if (map.containsValue("합격")) {

    System.out.println("합격 과목 있음");

} else {

    System.out.println("합격 과목 없음");

}

//초기화

map.clear();

System.out.println(map.size());


}//main


}


class MyHashMap{

private int index; //방번호

private String[] keys; //키값

private String[] values; //값

public MyHashMap() { //기본 생성자

this.index =-1;

this.keys = new String[100];

this.values = new String[100];

}

public void put(String key,String value) {

this.index++;

keys[this.index] = key;

values[this.index] = value;

if(getIndex(key)>-1) {

keys[getIndex(key)] = key;

values[getIndex(key)] = value;

}

}

public String get(String key) {

String value=values[getIndex(key)];

 

return value;

}

private 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+1;

}

public void remove(String key) {

int index = getIndex(key);

// this.keys[index] = null;

this.values[index] = null;

}

public boolean containKey(String key) {

for(int i=0;i<=this.index;i++) {

if(this.keys[i].equals(key)) {

return true;

}

}

return false;

}

public boolean containsValue(String value) {

for(int i=0;i<=this.index;i++) {

if(this.values[i].equals(value)) {

return true;

}

}

return false;

}

public void clear() {

for(int i=this.index;i>=0;i--) {

keys[i] = null;

values[i] = null;

}

this.index = -1;

}

}




//////////////결과값//////////////////

합격 //System.out.println(map.get("국어"));
불합격 //System.out.println(map.get("영어"));
보류 //System.out.println(map.get("수학"));

//System.out.println(map.size());

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

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

//검색(key)
국어 점수 있음 

//검색(value)
합격 과목 있음 

//초기화