Example #1
0
 @NotNull
 public HashPMap<K, V> plus(K key, V value) {
   ConsPStack<MapEntry<K, V>> entries = getEntries(key.hashCode());
   int size0 = entries.size();
   int i = keyIndexIn(entries, key);
   if (i != -1) entries = entries.minus(i);
   entries = entries.plus(new MapEntry<K, V>(key, value));
   return new HashPMap<K, V>(intMap.plus(key.hashCode(), entries), size - size0 + entries.size());
 }
Example #2
0
 /** Vrati hodnotu asociovanou s danym klicem nebo null, pokud dany klic v tabulce neni. */
 V get(K key) {
   if (storage[key.hashCode() % storage.length].isEmpty()) return null;
   Iterator iter = storage[key.hashCode() % storage.length].iterator();
   while (iter.hasNext()) {
     Pair<K, V> temp = (Pair<K, V>) iter.next();
     if (temp.key.equals(key)) {
       return temp.value;
     }
   }
   return null;
 }
 @Override
 public int hashCode() {
   int result = key.hashCode();
   result = 31 * result + (value != null ? value.hashCode() : 0);
   result = 31 * result + (oldValue != null ? oldValue.hashCode() : 0);
   return result;
 }
Example #4
0
  @Override
  public V put(final K key, final V value) {
    final Entry<K, V>[] table = this.table;
    final int hash = key.hashCode();
    final int index = HashUtil.indexFor(hash, table.length, shift, mask);

    for (Entry<K, V> e = table[index]; e != null; e = e.hashNext) {
      final K entryKey;
      if (e.keyHash == hash && ((entryKey = e.key) == key || entryKey.equals(key))) {
        moveToTop(e);
        return e.setValue(value);
      }
    }

    final Entry<K, V> e = new Entry<K, V>(key, value);
    e.hashNext = table[index];
    table[index] = e;
    final Entry<K, V> top = this.top;
    e.next = top;
    if (top != null) {
      top.previous = e;
    } else {
      back = e;
    }
    this.top = e;
    size = size + 1;

    if (removeEldestEntry(back)) {
      remove(back.key);
    } else if (size > capacity) {
      rehash(HashUtil.nextCapacity(capacity));
    }
    return null;
  }
Example #5
0
 /** Returns the hash code value for this map entry */
 @Override
 public int hashCode() {
   int code = 0;
   if (key != null) code = key.hashCode();
   if (value != null) code ^= value.hashCode();
   return code;
 }
  public V remove(K key) {
    int hashCode = key.hashCode();
    int index = hashCode & mask;
    if (key.equals(keyTable[index])) {
      keyTable[index] = null;
      V oldValue = valueTable[index];
      valueTable[index] = null;
      size--;
      return oldValue;
    }

    index = hash2(hashCode);
    if (key.equals(keyTable[index])) {
      keyTable[index] = null;
      V oldValue = valueTable[index];
      valueTable[index] = null;
      size--;
      return oldValue;
    }

    index = hash3(hashCode);
    if (key.equals(keyTable[index])) {
      keyTable[index] = null;
      V oldValue = valueTable[index];
      valueTable[index] = null;
      size--;
      return oldValue;
    }

    return removeStash(key);
  }
 @Override
 public V put(K key, V value) {
   V oldValue = null;
   int index = Math.abs(key.hashCode()) % capacity;
   if (buckets[index] == null) buckets[index] = new LinkedList<MapEntry<K, V>>();
   LinkedList<MapEntry<K, V>> bucket = buckets[index];
   MapEntry<K, V> pair = new MapEntry<K, V>(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 new
       found = true;
       break;
     }
   }
   if (!found) {
     if (count >= threshold) rehash();
     if (buckets[index] == null) buckets[index] = new LinkedList<MapEntry<K, V>>();
     buckets[index].add(pair);
     ++count;
   }
   return oldValue;
 }
  @SuppressWarnings({"unchecked", "rawtypes", "unused"})
  @Override
  public V put(K key, V value) {
    K k = (K) maskNull(key);
    int h = HashMap.hash(k.hashCode());
    Entry[] tab = getTable();
    int i = indexFor(h, tab.length);

    for (Entry<K, V> e = tab[i]; e != null; e = e.next) {
      if (h == e.hash && eq(k, e.get())) {
        V oldValue = e.value;
        if (value != oldValue) {
          e.value = value;
        }
        return oldValue;
      }
    }

    modCount++;
    Entry<K, V> e = tab[i];
    //		tab[i] = new Entry<K,V>(k, value, queue, h, e);
    if (++size >= threshold) {
      resize(tab.length * 2);
    }
    return null;
  }
 public V put(K key, V value) {
   V oldValue = null;
   int index = Math.abs(key.hashCode()) % SIZE;
   if (buckets[index] == null) buckets[index] = new ArrayList<MapEntry<K, V>>();
   ArrayList<MapEntry<K, V>> bucket = buckets[index];
   MapEntry<K, V> pair = new MapEntry<K, V>(key, value);
   boolean found = false;
   ListIterator<MapEntry<K, V>> it = bucket.listIterator();
   // int probes=0;
   while (it.hasNext()) {
     //	probes++;
     MapEntry<K, V> iPair = it.next();
     //  if(!iPair.getKey().equals(key)) System.out.println("HashCode collision on put, have
     // key:"+key+" hascode:"+key.hashCode()+" found key:"+iPair.getKey()+" hashcode:"+
     // iPair.getKey().hashCode());
     if (iPair.getKey().equals(key)) {
       oldValue = iPair.getValue();
       it.set(pair); // Replace old with new
       found = true;
       break;
     }
   }
   // System.out.println("put() probes for key "+ key+" :"+probes);
   if (!found) buckets[index].add(pair);
   return oldValue;
 }
Example #10
0
 /**
  * Special fast path for appending items to the end of the array without validation. The array
  * must already be large enough to contain the item.
  *
  * @hide
  */
 public void append(K key, V value) {
   int index = mSize;
   final int hash = key == null ? 0 : key.hashCode();
   if (index >= mHashes.length) {
     throw new IllegalStateException("Array is full");
   }
   if (index > 0 && mHashes[index - 1] > hash) {
     RuntimeException e = new RuntimeException("here");
     e.fillInStackTrace();
     Log.w(
         TAG,
         "New hash "
             + hash
             + " is before end of array hash "
             + mHashes[index - 1]
             + " at index "
             + index
             + " key "
             + key,
         e);
     put(key, value);
     return;
   }
   mSize = index + 1;
   mHashes[index] = hash;
   index <<= 1;
   mArray[index] = key;
   mArray[index + 1] = value;
 }
 public void handleOversizeMappingException(
     K key, OversizeMappingException cause, AtomicBoolean invokeValve)
     throws CacheAccessException {
   if (!map.shrinkOthers(key.hashCode())) {
     if (!invokeValve(invokeValve)) {
       for (Segment<K, OffHeapValueHolder<V>> segment : map.getSegments()) {
         Lock lock = segment.writeLock();
         lock.lock();
         try {
           for (K keyToEvict : segment.keySet()) {
             if (map.updateMetadata(keyToEvict, EhcacheSegmentFactory.EhcacheSegment.VETOED, 0)) {
               return;
             }
           }
         } finally {
           lock.unlock();
         }
       }
       throw new CacheAccessException(
           "The element with key '"
               + key
               + "' is too large to be stored"
               + " in this offheap store.",
           cause);
     }
   }
 }
 @Override
 public ReplaceStatus replace(final K key, final V oldValue, final V newValue)
     throws StoreAccessException {
   conditionalReplaceObserver.begin();
   try {
     ConditionalReplaceOperation<K, V> operation =
         new ConditionalReplaceOperation<K, V>(
             key, oldValue, newValue, timeSource.getTimeMillis());
     ByteBuffer payload = codec.encode(operation);
     Chain chain = storeProxy.getAndAppend(key.hashCode(), payload);
     ResolvedChain<K, V> resolvedChain = resolver.resolve(chain, key, timeSource.getTimeMillis());
     Result<V> result = resolvedChain.getResolvedResult(key);
     if (result != null) {
       if (oldValue.equals(result.getValue())) {
         conditionalReplaceObserver.end(StoreOperationOutcomes.ConditionalReplaceOutcome.REPLACED);
         return ReplaceStatus.HIT;
       } else {
         conditionalReplaceObserver.end(StoreOperationOutcomes.ConditionalReplaceOutcome.MISS);
         return ReplaceStatus.MISS_PRESENT;
       }
     } else {
       conditionalReplaceObserver.end(StoreOperationOutcomes.ConditionalReplaceOutcome.MISS);
       return ReplaceStatus.MISS_NOT_PRESENT;
     }
   } catch (RuntimeException re) {
     handleRuntimeException(re);
     return null;
   }
 }
Example #13
0
 @Override
 public int hashCode() {
   int result = (int) (timestamp ^ (timestamp >>> 32));
   result = 31 * result + key.hashCode();
   result = 31 * result + window.hashCode();
   return result;
 }
  /**
   * {@inheritDoc}
   *
   * <p>This method will, on a best-effort basis, throw a {@link
   * java.util.ConcurrentModificationException} if the remapping function modified this map during
   * computation.
   *
   * @throws ConcurrentModificationException if it is detected that the remapping function modified
   *     this map
   */
  @Override
  public synchronized V computeIfPresent(
      K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
    Objects.requireNonNull(remappingFunction);

    Entry<?, ?> tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    Entry<K, V> e = (Entry<K, V>) tab[index];
    for (Entry<K, V> prev = null; e != null; prev = e, e = e.next) {
      if (e.hash == hash && e.key.equals(key)) {
        int mc = modCount;
        V newValue = remappingFunction.apply(key, e.value);
        if (mc != modCount) {
          throw new ConcurrentModificationException();
        }
        if (newValue == null) {
          if (prev != null) {
            prev.next = e.next;
          } else {
            tab[index] = e.next;
          }
          modCount = mc + 1;
          count--;
        } else {
          e.value = newValue;
        }
        return newValue;
      }
    }
    return null;
  }
Example #15
0
  /**
   * Maps the specified <code>key</code> to the specified <code>value</code> in this hashtable.
   * Neither the key nor the value can be <code>null</code>.
   *
   * <p>The value can be retrieved by calling the <code>get</code> method with a key that is equal
   * to the original key.
   *
   * @param key the hashtable key
   * @param value the value
   * @return the previous value of the specified key in this hashtable, or <code>null</code> if it
   *     did not have one
   * @exception NullPointerException if the key or value is <code>null</code>
   * @see Object#equals(Object)
   * @see #get(Object)
   */
  public synchronized V put(K key, V value) {
    // Make sure the value is not null
    if (value == null) {
      throw new NullPointerException();
    }

    // Makes sure the key is not already in the hashtable.
    Entry tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    for (Entry<K, V> e = tab[index]; e != null; e = e.next) {
      if ((e.hash == hash) && e.key.equals(key)) {
        V old = e.value;
        e.value = value;
        return old;
      }
    }

    modCount++;
    if (count >= threshold) {
      // Rehash the table if the threshold is exceeded
      rehash();

      tab = table;
      index = (hash & 0x7FFFFFFF) % tab.length;
    }

    // Creates the new entry.
    Entry<K, V> e = tab[index];
    tab[index] = new Entry<>(hash, key, value, e);
    count++;
    return null;
  }
  /**
   * {@inheritDoc}
   *
   * <p>This method will, on a best-effort basis, throw a {@link
   * java.util.ConcurrentModificationException} if the mapping function modified this map during
   * computation.
   *
   * @throws ConcurrentModificationException if it is detected that the mapping function modified
   *     this map
   */
  @Override
  public synchronized V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
    Objects.requireNonNull(mappingFunction);

    Entry<?, ?> tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    Entry<K, V> e = (Entry<K, V>) tab[index];
    for (; e != null; e = e.next) {
      if (e.hash == hash && e.key.equals(key)) {
        // Hashtable not accept null value
        return e.value;
      }
    }

    int mc = modCount;
    V newValue = mappingFunction.apply(key);
    if (mc != modCount) {
      throw new ConcurrentModificationException();
    }
    if (newValue != null) {
      addEntry(hash, key, newValue, index);
    }

    return newValue;
  }
Example #17
0
  /** Skips checks for existing keys. */
  private void putResize(K key, int value) {
    // Check for empty buckets.
    int hashCode = key.hashCode();
    int index1 = hashCode & mask;
    K key1 = keyTable[index1];
    if (key1 == null) {
      keyTable[index1] = key;
      valueTable[index1] = value;
      if (size++ >= threshold) resize(capacity << 1);
      return;
    }

    int index2 = hash2(hashCode);
    K key2 = keyTable[index2];
    if (key2 == null) {
      keyTable[index2] = key;
      valueTable[index2] = value;
      if (size++ >= threshold) resize(capacity << 1);
      return;
    }

    int index3 = hash3(hashCode);
    K key3 = keyTable[index3];
    if (key3 == null) {
      keyTable[index3] = key;
      valueTable[index3] = value;
      if (size++ >= threshold) resize(capacity << 1);
      return;
    }

    push(key, value, index1, key1, index2, key2, index3, key3);
  }
Example #18
0
  public int remove(K key, int defaultValue) {
    int hashCode = key.hashCode();
    int index = hashCode & mask;
    if (key.equals(keyTable[index])) {
      keyTable[index] = null;
      int oldValue = valueTable[index];
      size--;
      return oldValue;
    }

    index = hash2(hashCode);
    if (key.equals(keyTable[index])) {
      keyTable[index] = null;
      int oldValue = valueTable[index];
      size--;
      return oldValue;
    }

    index = hash3(hashCode);
    if (key.equals(keyTable[index])) {
      keyTable[index] = null;
      int oldValue = valueTable[index];
      size--;
      return oldValue;
    }

    return removeStash(key, defaultValue);
  }
  /** {@inheritDoc} */
  @Override
  public V remove(K key) {
    Node node = find(key.hashCode());
    if (node == null) return null;
    if (node instanceof ArrayNode) return null;

    KeyValueNode<V> kvNode = (KeyValueNode<V>) node;
    V value = kvNode.value;
    if (node.parent == null) {
      // If parent is null, removing the root
      root = null;
    } else {
      ArrayNode parent = node.parent;
      // Remove child from parent
      int position = getPosition(parent.height, node.key);
      parent.removeChild(position);
      // Go back up the tree, pruning any array nodes which no longer have children.
      int numOfChildren = parent.getNumberOfChildren();
      while (numOfChildren == 0) {
        node = parent;
        parent = node.parent;
        if (parent == null) {
          // Reached root of the tree, need to stop
          root = null;
          break;
        }
        position = getPosition(parent.height, node.key);
        parent.removeChild(position);
        numOfChildren = parent.getNumberOfChildren();
      }
    }
    size--;
    return value;
  }
Example #20
0
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((key == null) ? 0 : key.hashCode());
   return result;
 }
Example #21
0
  /**
   * Associate the specified value with the specified key in this {@code Hashtable}. If the key
   * already exists, the old value is replaced. The key and value cannot be null.
   *
   * @param key the key to add.
   * @param value the value to add.
   * @return the old value associated with the specified key, or {@code null} if the key did not
   *     exist.
   * @see #elements
   * @see #get
   * @see #keys
   * @see java.lang.Object#equals
   */
  public synchronized V put(K key, V value) {
    if (key == null) {
      throw new NullPointerException("key == null");
    } else if (value == null) {
      throw new NullPointerException("value == null");
    }
    int hash = secondaryHash(key.hashCode());
    HashtableEntry<K, V>[] tab = table;
    int index = hash & (tab.length - 1);
    HashtableEntry<K, V> first = tab[index];
    for (HashtableEntry<K, V> e = first; e != null; e = e.next) {
      if (e.hash == hash && key.equals(e.key)) {
        V oldValue = e.value;
        e.value = value;
        return oldValue;
      }
    }

    // No entry for key is present; create one
    modCount++;
    if (size++ > threshold) {
      rehash(); // Does nothing!!
      tab = doubleCapacity();
      index = hash & (tab.length - 1);
      first = tab[index];
    }
    tab[index] = new HashtableEntry<K, V>(key, value, hash, first);
    return null;
  }
Example #22
0
 private int index(K key) {
   int index = key.hashCode() % table.length;
   if (index < 0) {
     index = index + table.length;
   }
   return index;
 }
 @Override
 public int hashCode() {
   if (key == null || value == null) {
     return 0;
   }
   return key.hashCode() ^ value.hashCode();
 }
 /** {@inheritDoc} */
 @Override
 public V get(K key) {
   Node node = find(key.hashCode());
   if (node == null) return null;
   if (node instanceof KeyValueNode) return ((KeyValueNode<V>) node).value;
   return null;
 }
Example #25
0
  public void put(K key, float value) {
    if (key == null) throw new IllegalArgumentException("key cannot be null.");
    K[] keyTable = this.keyTable;

    // Check for existing keys.
    int hashCode = key.hashCode();
    int index1 = hashCode & mask;
    K key1 = keyTable[index1];
    if (key.equals(key1)) {
      valueTable[index1] = value;
      return;
    }

    int index2 = hash2(hashCode);
    K key2 = keyTable[index2];
    if (key.equals(key2)) {
      valueTable[index2] = value;
      return;
    }

    int index3 = hash3(hashCode);
    K key3 = keyTable[index3];
    if (key.equals(key3)) {
      valueTable[index3] = value;
      return;
    }

    // Update key in the stash.
    for (int i = capacity, n = i + stashSize; i < n; i++) {
      if (key.equals(keyTable[i])) {
        valueTable[i] = value;
        return;
      }
    }

    // Check for empty buckets.
    if (key1 == null) {
      keyTable[index1] = key;
      valueTable[index1] = value;
      if (size++ >= threshold) resize(capacity << 1);
      return;
    }

    if (key2 == null) {
      keyTable[index2] = key;
      valueTable[index2] = value;
      if (size++ >= threshold) resize(capacity << 1);
      return;
    }

    if (key3 == null) {
      keyTable[index3] = key;
      valueTable[index3] = value;
      if (size++ >= threshold) resize(capacity << 1);
      return;
    }

    push(key, value, index1, key1, index2, key2, index3, key3);
  }
 /**
  *
  *
  * <blockquote>
  *
  * If a collision occurs, a second hash function is applied to x and then multiplied by i.
  *
  * </blockquote>
  *
  * @param key
  * @return int value
  */
 private int hashFn2(K key) {
   if (null == key) {
     return 0;
   }
   int x = key.hashCode(); // same hash value retrieved
   int hash2OfX = 1 + (x % primeValBelowSize);
   return hash2OfX;
 }
 /**
  * This will compute the first hash value.
  *
  * @param key
  * @return int value
  */
 private int hashFn1(K key) {
   if (null == key) {
     return 0;
   }
   int x = key.hashCode();
   int hash1OfX = x % values.length; // h1(k) = k%m ( m is size)
   return hash1OfX;
 }
 @Override
 public int hashCode() {
   int result = leftChild.hashCode();
   result = 31 * result + rightChild.hashCode();
   result = 31 * result + key.hashCode();
   result = 31 * result + (value != null ? value.hashCode() : 0);
   return result;
 }
 protected File getFile(K key) {
   File base = null;
   if (storageDirectories != null) {
     int hash = (key.hashCode() & 0x7FFFFFFF) % storageDirectories.length;
     base = storageDirectories[hash];
   } else {
     base = baseDirectory;
   }
   return new File(base, String.valueOf(key) + ".ser");
 }
Example #30
0
 public V putIfAbsent(K key, V value) {
   if (value == null) throw new NullPointerException();
   int hash = hash(key.hashCode());
   try {
     return segmentFor(hash).put(key, hash, value, true);
   } catch (LRUHashMapException e) {
     e.printStackTrace();
   }
   return value;
 }