Advertisement
Guest User

Untitled

a guest
Nov 28th, 2016
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. package cubicchunks.util;
  2.  
  3. import java.util.function.ToDoubleFunction;
  4. import java.util.function.ToIntFunction;
  5.  
  6. public class HashCacheDoubles<K> {
  7.     private final double[] cache;
  8.     private final K[] keys;
  9.     private final ToIntFunction<K> hashFunction;
  10.     private final ToDoubleFunction<K> source;
  11.  
  12.     @SuppressWarnings("uncecked")
  13.     private HashCacheDoubles(int size, ToIntFunction<K> hashCode, ToDoubleFunction<K> source) {
  14.         this.cache = new double[size];
  15.         this.keys =  (K[]) new Object[size];
  16.         this.hashFunction = hashCode;
  17.         this.source = source;
  18.     }
  19.  
  20.     public double get(K key) {
  21.         int index = index(hashFunction.applyAsInt(key));
  22.         if (!key.equals(keys[index])) {
  23.             keys[index] = key;
  24.             cache[index] = source.applyAsDouble(key);
  25.         }
  26.         return cache[index];
  27.     }
  28.  
  29.     private int index(int hash) {
  30.         return Math.floorMod(hash, cache.length);
  31.     }
  32.  
  33.     public static <K> HashCacheDoubles<K> create(int size, ToDoubleFunction<K> source) {
  34.         return create(size, k->k.hashCode(), source);
  35.     }
  36.  
  37.     public static <K> HashCacheDoubles<K> create(int size, ToIntFunction<K> hashCode, ToDoubleFunction<K> source) {
  38.         return new HashCacheDoubles<K>(size, hashCode, source);
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement