简体   繁体   中英

Writing put method for hashmap

I am currently writing a put method for a hashmap implementation I have. This is what I have so far:

@Override
    public boolean put(K key, V value) throws IllegalArgumentException {
        // can also use key.hashCode() assuming key is not null
        for(int i = 0; i < buckets.length; i += 1) {
            buckets[i] = new ArrayList<HashMapEntry<K, V>>();
        }
        if(key == null) {
            throw new IllegalArgumentException(ILLEGAL_ARG_NULL_KEY);
        }
        int keyHash = key.hashCode();
        int index = Math.abs(keyHash % capacity);
        if(buckets[index].equals(key)) {
            return(false);
        } else {
            buckets[index].add(new HashMapEntry<K, V>(key, value));
            size += 1;
            if(capacity / size >= loadFactor) {
                expandCapacity();
            }
            return(true);
        }
    }

The put method should do as follows:

/**
     * Replaces the value that maps to the key if it is present
     * @param key The key whose mapped value is being replaced
     * @param newValue The value to replace the existing value with
     * @return true if the key was in this DefaultMap
     * @throws IllegalArgument exception if the key is null
     */

When testing, my method so far does none of this except correctly throwing the IllegalArgumentException if the key being passed thru is null. I am stuck on how to do the rest part of this method, so any help with justification is appreciated!

Java code I am working with: MyHashMap.java DefaultMap.java MyHashMapTest.java

At the very beginning of your method, you're cleaning out all the previous data from the buckets array.

for (int i = 0; i < buckets.length; i += 1) {
    buckets[i] = new ArrayList<HashMapEntry<K, V>>();
}

Which is wrong, put() should not affect existing data.

The following condition is always false , HashMapEntry can't be equal to a Key, hence it's pointless.

if (buckets[index].equals(key))

According to your requirements:

Replaces the value that maps to the key if it is present

...

@return true if the key was in this DefaultMap

So you need to access the target bucket, and iterate over its list to find out if the given Key exists. If the Key was found, then you need to replace the Value associated with it with the given Value and return true . Otherwise, return false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM