상세 컨텐츠

본문 제목

[Data Structure] 자료구조-Hash Table(해시 테이블)

Data Structure 캐기

by Atlas 2022. 2. 7. 21:57

본문

728x90
반응형

시나리오 : Hash Table 관련해서 리마인드 해 봄. 

전체 소스

import java.util.LinkedList;

class HashTable {
    // HashTable에 저장할 데이터
    class Node {
        String key; // 검색할 키
        String value; // 검색 결과

        public Node(String key, String value){
            this.key = key;
            this.value = value;
        }

        String value() {
            return value;
        }

        void value(String value){
            this.value = value;
        }
    }

    LinkedList<Node>[] data;
    // 선언하는 순간 크기 설정
    HashTable(int size) {
        this.data = new LinkedList[size];
    }

    // 해시함수
     int getHashCode(String key) {
     	int hashcode = 0;
     	for (char c : key.toCharArray()) {
     		hashcode += c;
     	}
     	return hashcode;
     }

     // 배열 인덱스로 변환
     int convertToIndex(int hashCode) {
        return hashCode % data.length;
     }

     //검색 키를 가지고 해당 노드 리턴
     Node searchKey(LinkedList<Node> list, String key){
        if (list == null) return  null;
        for (Node node : list) {
            if (node.key.equals(key)){
                return  node;
            }
        }
        return  null;
     }
    // 데이터 저장
     void put(String key, String value){
        int hasCode = getHashCode(key);
        int index = convertToIndex(hasCode);
        LinkedList<Node> list = data[index];

        if (list == null) {
            list = new LinkedList<Node>();
            data[index] = list;
        }

        Node node = searchKey(list,key);
        if (node == null) {
            list.addLast(new Node(key, value));
        }else{
            //중복처리
            node.value(value);
        }
     }
    // 데이터 가져오기
     String get(String key) {
        int hashCode = getHashCode(key);
        int index = convertToIndex(hashCode);
        LinkedList<Node> list = data[index];

        Node node = searchKey(list,key);
        return  node == null? "Not Found" : node.value();
     }


}

public class Demo {
    public static void main(String[] args) {
        System.out.println("hello word");

        HashTable h = new HashTable(5);
        h.put("a","hello");
        h.put("t","world");
        h.put("l","nice");
        h.put("!","to");
        h.put("s","meet you");

        System.out.println(h.get("a"));
        System.out.println(h.get("t"));
        System.out.println(h.get("l"));
        System.out.println(h.get("!"));
        System.out.println(h.get("s"));
        System.out.println(h.get("-"));

    }
}

 

마무리 

데이터 구조랑 알고리즘은 언제 해도 좋음! 

반응형

댓글 영역