gpt4 book ai didi

java - 试图理解 hashmap 数据结构

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:14:04 25 4
gpt4 key购买 nike

我正在做一项涉及构建 HashMap 数据结构的家庭作业,但我不理解提供给我们的一行代码。程序中初始化一个变量如下:

private Map<K,V>[] buckets;

我知道在 hashmap 中使用 buckets 是什么概念,但我如何使用 map 数组来创建 buckets?当我查看这段代码时,似乎我需要创建一个 HashMap 数组,但这根本没有意义。

如果您需要更多信息,请告诉我。

非常感谢任何帮助。

下面是提供的代码。

package cs2321;

import net.datastructures.*;

public class HashMap<K, V> implements Map<K, V> {

private Map<K,V>[] buckets;

protected final int mDefaultHashSize = 1021;

/**
* Constructor that takes a hash size
* @param hashsize The number of buckets to initialize
* in the HashMap
*/
public HashMap(int hashsize){
// TODO: Be sure to initialize the bucket array
// using the hashsize given as the number of buckets
}

public HashMap(){
// TODO: Be sure to initialize the bucket array
// using the default hash size provided.
}


public Iterable<Entry<K, V>> entrySet() {
// TODO Auto-generated method stub
return null;
}

public V get(K key) throws InvalidKeyException {
// TODO Auto-generated method stub
return null;
}

public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}

public Iterable<K> keySet() {
// TODO Auto-generated method stub
return null;
}

public V put(K key, V value) throws InvalidKeyException {
// TODO Auto-generated method stub
return null;
}

public V remove(K key) throws InvalidKeyException {
// TODO Auto-generated method stub
return null;
}

public int size() {
// TODO Auto-generated method stub
return 0;
}

public Iterable<V> values() {
// TODO Auto-generated method stub
return null;
}

最佳答案

这是一个 HashMap 数组,用于演示 HashMap 的工作原理。研究它并告诉我们它是如何工作的以及为什么 HashMaps 被如此广泛地使用?

public class Test {
static private Map<String,String>[] buckets;
static int numberOfBuckets = 3;
static public void main(String...strings) {
buckets = new Map[numberOfBuckets];
for (int x=0; x!=numberOfBuckets; x++) {
buckets[x]=new HashMap<String,String>();
}
String s1 = "one ijsiji jdj i";
String s2 = "two ijs42i jdj i";
String s3 = "th3 ijsiji 42j i";
String s4 = "i42 ji jdj i";
buckets[(Math.abs(s1.hashCode()) % numberOfBuckets)].put(s1,"");
buckets[(Math.abs(s2.hashCode()) % numberOfBuckets)].put(s2,"");
buckets[(Math.abs(s3.hashCode()) % numberOfBuckets)].put(s3,"");
buckets[(Math.abs(s4.hashCode()) % numberOfBuckets)].put(s4,"");
for (int x=0; x!=numberOfBuckets; x++) {
System.out.println(buckets[x]);
}
}
}

输出

{two ijs42i jdj i=}
{one ijsiji jdj i=, i42 ji jdj i=}
{th3 ijsiji 42j i=}

关于java - 试图理解 hashmap 数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9678321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com