Programming/자료구조
Hash_Map(해쉬 맵)
Futurism
2022. 12. 19. 09:24
728x90
Hash table : key에 해당하는 hash 값 저장
hash map : key, hash값 둘다 저장
- 해시 충돌이 일어날 경우 추가로 삽입한다(연결리스트 스택 으로 구현)
- hashcode 함수를 이용할경우 음수 반환으로 이루어지는 경우가 있다. 절댓값 계산이 필요함
public class Node {
String key;
int value;
Node next;
Node() {
this.key = null;
this.value = 0;
this.next = null;
}
Node(String key, int value) {
this.key = key;
this.value = value;
}
}
public class Act {
Node[] map = { new Node(), new Node(), new Node(), new Node(), new Node(), new Node() };
void insert(String key, int value) {// 중복된 해시값일 경우 스택과 같이 데이터를 추가한다
Node pre = map[Math.abs(key.hashCode() % map.length)].next;
Node no = new Node(key, value);
map[Math.abs(key.hashCode() % map.length)].next = no;
no.next = pre;
}
void pr(String key) {
Node search = null;
if (map[Math.abs(key.hashCode() % map.length)].next != null)
search = map[Math.abs(key.hashCode() % map.length)].next;
else {
System.out.println(key + "는 데이터 없음");
return;
}
while (true) {
if (search.key != key) {
if (search.next == null) {
System.out.println(key + "는 데이터 없음");
break;
} else {
search = search.next;
}
} else {
System.out.println(search.key);
System.out.println(search.value);
break;
}
}
}
}
public class Tables {
public static void main(String[] args) {
Act ac = new Act();
ac.insert("haha", 1);
ac.insert("seung", 2);
ac.insert("hyuk", 3);
ac.insert("park", 4);
ac.insert("jun", 5);
/*
System.out.println(ac.map[0].next.key);
System.out.println(ac.map[0].next.value);
System.out.println(ac.map[0].next.next.key);
System.out.println(ac.map[0].next.next.value);
System.out.println(ac.map[0].next.next.next.key);
System.out.println(ac.map[0].next.next.next.value);
*/
ac.pr("haha");
ac.pr("seung");
ac.pr("hyuk");
ac.pr("park");
ac.pr("jun");
ac.pr("qweqwwq4"); // 없는 데이터
//System.out.println("seung".hashCode()%3);
}
}
728x90