Example #1
0
  /**
   * insert {@code key}
   *
   * @return {@code true} if this caused a collision
   */
  boolean insert(T key) {
    long h = hash_.hash(key);
    int idx = (int) (h % table_.size());
    SList<T> bucket = table_.at(idx);
    if (bucket.empty()) {
      ++n_;
      bucket.push_front(key);
      recordInsert(idx);
      if (verbose) System.err.println("SimpleHashTable: insert " + key + " @ " + idx);
      return false;
    } else if (onCollision_ == null) { // separate chaining
      ++n_;
      bucket.push_front(key);
      recordInsert(idx);
      ++nCollisions_;
      if (verbose)
        System.err.println(
            "SimpleHashTable: insert "
                + key
                + " @ "
                + idx
                + " (bucket size="
                + bucket.size()
                + ")");
      return true;
    } else {
      for (int j = 1; j < table_.size(); ++j) {
        if (verbose) System.err.println("SimpleHashTable: insert " + key + " with " + onCollision_);

        h = onCollision_.newHash(this, key, h, j);

        if (verbose) System.err.print("SimpleHashTable: " + idx + " occupied => ");

        idx = (int) (h % table_.size());

        if (verbose) System.err.println(idx);

        ++nCollisions_;

        if ((bucket = table_.at(idx)).empty()) {
          ++n_;
          bucket.push_front(key);
          recordInsert(idx);
          return true;
        }
      }
      // give up after N tries !
      throw new RuntimeException("collision handling failed!");
    }
  }