예제


<aside> 🪄

package collection.set;

public class StringHashMain {

    static final int CAPACITY = 10;

    public static void main(String[] args) {

        char charA = 'A';
        char charB = 'B';
        System.out.println("charA" + " = " + (int)charA);
        System.out.println("charB" + " = " + (int)charB);

        System.out.println("hashCode(A) = " + hashCode("A"));
        System.out.println("hashCode(B) = " + hashCode("B"));
        System.out.println("hashCode(AB) = " + hashCode("AB"));

        System.out.println("hashIndex(A) = " + hashIndex(hashCode("A")));
        System.out.println("hashIndex(B) = " + hashIndex(hashCode("B")));
        System.out.println("hashIndex(AB) = " + hashIndex(hashCode("AB")));
    }

    static int hashCode(String str) {
		    //문자열형을 문자형으로 바꿈
        char[] charArray = str.toCharArray();
        int sum = 0;
        for (char c : charArray) {
            sum += c; // sum = sum + (int) c와 동일
        }
        return sum;
    }

    static int hashIndex(int value) {
        return value % CAPACITY;
    }
}
출력

charA = 65
charB = 66
hashCode(A) = 65
hashCode(B) = 66
hashCode(AB) = 131
hashIndex(A) = 5
hashIndex(B) = 6
hashIndex(AB) = 1

image.png