Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public V remove(K key) {
- int hash = hash(key);
- Node<K, V> bucketElement = map[hash];
- int hashKey = key == null ? -1 : key.hashCode();
- try {
- int depth = 0;
- while (bucketElement != null) {
- if (bucketElement.hash == hashKey) {
- if (bucketElement.hash != -1 && bucketElement.key.equals(key)) {
- return unlinkNode(bucketElement, depth, hash);
- } else if (bucketElement.hash == -1) {
- return unlinkNode(bucketElement, depth, hash);
- }
- }
- bucketElement = bucketElement.next;
- depth++;
- }
- throw new Exception();
- } catch (Exception e) {
- throw new NoSuchElementException("Element with key " + key + " not found");
- }
- }
- private V unlinkNode(Node<K, V> nodeToUnlink, int depth, int hash) {
- V savedValue = nodeToUnlink.value;
- Node<K, V> nextBucketElement = nodeToUnlink.next;
- Node<K, V> previousBucketElement = map[hash];
- if (depth == 0 && nextBucketElement != null) {
- map[hash] = nextBucketElement;
- return savedValue;
- } else if (depth == 0) {
- map[hash] = null;
- return savedValue;
- }
- while (depth > 1) {
- previousBucketElement = previousBucketElement.next;
- depth--;
- }
- previousBucketElement.next = nextBucketElement;
- return savedValue;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement