Advertisement
Guest User

Untitled

a guest
Nov 19th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.56 KB | None | 0 0
  1. public V remove(K key) {
  2.         int hash = hash(key);
  3.         Node<K, V> bucketElement = map[hash];
  4.         int hashKey = key == null ? -1 : key.hashCode();
  5.         try {
  6.             int depth = 0;
  7.             while (bucketElement != null) {
  8.                 if (bucketElement.hash == hashKey) {
  9.                     if (bucketElement.hash != -1 && bucketElement.key.equals(key)) {
  10.                         return unlinkNode(bucketElement, depth, hash);
  11.                     } else if (bucketElement.hash == -1) {
  12.                         return unlinkNode(bucketElement, depth, hash);
  13.                     }
  14.                 }
  15.                 bucketElement = bucketElement.next;
  16.                 depth++;
  17.             }
  18.             throw new Exception();
  19.         } catch (Exception e) {
  20.             throw new NoSuchElementException("Element with key " +  key + " not found");
  21.         }
  22.     }
  23.  
  24.     private V unlinkNode(Node<K, V> nodeToUnlink, int depth, int hash) {
  25.         V savedValue = nodeToUnlink.value;
  26.         Node<K, V> nextBucketElement = nodeToUnlink.next;
  27.         Node<K, V> previousBucketElement = map[hash];
  28.         if (depth == 0 && nextBucketElement != null) {
  29.             map[hash] = nextBucketElement;
  30.             return savedValue;
  31.         } else if (depth == 0) {
  32.             map[hash] = null;
  33.             return savedValue;
  34.         }
  35.         while (depth > 1) {
  36.             previousBucketElement = previousBucketElement.next;
  37.             depth--;
  38.         }
  39.         previousBucketElement.next = nextBucketElement;
  40.         return savedValue;
  41.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement