import java.util.*; public class HashAlgorithm { public static int hash(String str, int size) { int hashCode = 0; for (int i = 0; i < str.length(); i++) { hashCode = 31 * hashCode + str.charAt(i); // 31是一个素数,用于加权 } return hashCode % size; // 取余得到对应的桶 } public static HashSet getValues(int key) { return new HashSet(); } public static void main(String[] args) { String[] strs = {"apple", "banana", "orange", "pear", "grape", "watermelon", "pineapple"}; int size = 10; // 假设有10个桶 Map<Integer, Set<String>> map = new HashMap<>(); for (String str : strs) { int index = hash(str, size); // if (!map.containsKey(index)) { // map.put(index, new ArrayList<>()); // } map.computeIfPresent(index,key -> getValues(key)).add(str); // map.get(index).add(str); } System.out.println(map.toString()); // for (int i = 0; i < size; i++) { // if (map.containsKey(i)) { // System.out.println("Bucket " + i + ": " + map.get(i)); // } // } } }
简易Hash
最新推荐文章于 2024-07-20 09:21:06 发布