繁体   English   中英

为 hashmap 编写 put 方法

[英]Writing put method for hashmap

我目前正在为我拥有的 hashmap 实现编写一个 put 方法。 这是我到目前为止所拥有的:

@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);
        }
    }

put 方法应执行以下操作:

/**
     * 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
     */

测试时,我的方法到目前为止除了正确抛出 IllegalArgumentException 之外,如果传递的密钥是 null,则没有执行任何操作。我一直在研究如何执行此方法的 rest 部分,因此感谢任何有关证明的帮助!

Java 我正在使用的代码: MyHashMap.java DefaultMap.java MyHashMapTest.java

在您的方法的最开始,您要从buckets数组中清除所有以前的数据。

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

这是错误的, put()不应影响现有数据。

以下条件始终为falseHashMapEntry不能等于 Key,因此没有意义。

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

根据您的要求:

替换映射到键的值(如果存在)

...

@return true如果键在此 DefaultMap 中

因此,您需要访问目标存储桶,并遍历其列表以查明给定的Key是否存在。 如果找到 Key,则需要用给定的Value替换与其关联的Value并返回true 否则返回false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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