// equalshashcode/SimpleHashMap.java// (c)2017 MindView LLC: see Copyright.txt// We make no guarantees that this code is fit for any purpose.// Visit http://OnJava8.com for more book information.// A demonstration hashed Mapimport java.util.*;import onjava.*;publicclass SimpleHashMap<K, V> extends AbstractMap<K, V> {// Choose a prime number for the hash table// size, to achieve a uniform distribution:static final int SIZE = 997;// You can't have a physical array of generics,// but you can upcast to one:@SuppressWarnings("unchecked")LinkedList<MapEntry<K, V>>[] buckets =new LinkedList[SIZE];@Overridepublic V put(K key, V value) {V oldValue = null;int index = Math.abs(key.hashCode()) % SIZE;if(buckets[index] == null)buckets[index] = new LinkedList<>();LinkedList<MapEntry<K, V>> bucket = buckets[index];MapEntry<K, V> pair = new MapEntry<>(key, value);boolean found = false;ListIterator<MapEntry<K, V>> it =bucket.listIterator();while(it.hasNext()) {MapEntry<K, V> iPair = it.next();if(iPair.getKey().equals(key)) {oldValue = iPair.getValue();it.set(pair); // Replace old with newfound = true;break;}}if(!found)buckets[index].add(pair);return oldValue;}@Overridepublic V get(Object key) {int index = Math.abs(key.hashCode()) % SIZE;if(buckets[index] == null) return null;for(MapEntry<K, V> iPair : buckets[index])if(iPair.getKey().equals(key))return iPair.getValue();return null;}@Overridepublic Set<Map.Entry<K, V>> entrySet() {Set<Map.Entry<K, V>> set= new HashSet<>();for(LinkedList<MapEntry<K, V>> bucket : buckets) {if(bucket == null) continue;for(MapEntry<K, V> mpair : bucket)set.add(mpair);}return set;}public static void main(String[] args) {SimpleHashMap<String,String> m =new SimpleHashMap<>();m.putAll(Countries.capitals(8));m.forEach((k, v) ->System.out.println(k + "=" + v));System.out.println(m.get("BENIN"));m.entrySet().forEach(System.out::println);}}/* Output:CAMEROON=YaoundeANGOLA=LuandaBURKINA FASO=OuagadougouBURUNDI=BujumburaALGERIA=AlgiersBENIN=Porto-NovoCAPE VERDE=PraiaBOTSWANA=GaberonePorto-NovoCAMEROON=YaoundeANGOLA=LuandaBURKINA FASO=OuagadougouBURUNDI=BujumburaALGERIA=AlgiersBENIN=Porto-NovoCAPE VERDE=PraiaBOTSWANA=Gaberone*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。