java - 我需要实现一个方法,我可以从值和方法删除中获取键
问题描述
我有一个类 MapEntry 来实现 Hashmap。我需要实现一个方法,我可以从值和方法删除中获取键。我知道 HashMap 没有实现 getValue 这样的方法,但我的教授要求这样做。我是编程新手,现在对我来说有点困难。我会很感激任何帮助。
public class MapEntry<K,V> {
MapEntry<K,V> next;
K key;
V value;
public MapEntry(K key, V value) {
this.setKey(key);
this.setValue(value);
}
public void setKey( K key){
this.key=key;
}
public void setValue(V value){
this.value=value;
}
public K getKey(){
return key;
}
public V getValue(){
return value;
}
public void setNext(MapEntry<K,V> next) {
this.next = next;
}
public MapEntry<K, V> getNext() {
return next;
}
}
public class HashMap{
private int DEFAULT_CAPACITY = 10;
private MapEntry<String,Double>[] Hash;
private int size;
public HashMap() {
Hash = new MapEntry[DEFAULT_CAPACITY];
}
public boolean isEmpty(){
if(size!= 0){
return false;
}
else{
return true;
}
}
public int getHashCode(String key){
int bucketIndex = key.hashCode()%Hash.length;
return bucketIndex;
}
public Double get(String key){
if(key == null){
try {
throw new IllegalAccessException("Null key");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
MapEntry<String,Double> entry = Hash[getHashCode(key)];
while (entry != null && !key.equals(entry.getKey()))
entry = entry.getNext();
if(entry != null)
return entry.getValue();
else
return null;
}
}
public void put(String key, double value){
int keyBucket =hash(key);
MapEntry<String,Double> temp = Hash[keyBucket];
while (temp !=null){
if((temp.key == null && key == null)
|| (temp.key != null && temp.key.equals(key))){
temp.value = value;
return;
}
temp = temp.next;
}
Hash[keyBucket] = new MapEntry<String, Double>(key,value);
size++;
}
public void delete (String key) throws IllegalAccessException {
if(key == null){
throw new IllegalAccessException("Null key");
}
}
private int hash(String key){
if(key == null){
return 0;
}else {
return Math.abs(key.hashCode()% this.Hash.length);
}
}
public static void main(String[] args) {
HashMap hashMap = new HashMap();
hashMap.put("value", 2.2);
hashMap.put("bob", 2.3);
System.out.println(hashMap.get("value"));
System.out.println(hashMap.get("bob"));
System.out.println(hashMap.size);
System.out.println(hashMap.getHashCode("value"));
System.out.println(hashMap.getHashCode("bob"));
System.out.println(hashMap.isEmpty());
}
}
解决方案
我认为基本算法将是:
- 一个一个地遍历所有的值
- 如果您的值与所需结果匹配,请从该条目中检索密钥。
- 要删除该条目,只需删除该条目
注意:如果您有多个相同值的条目,则无法正常工作。
推荐阅读
- python - 当 MSE 函数急切执行时,Tensor.name 没有意义
- javascript - 错误getCode是什么意思?
- javascript - 如何制作打字动画,可以中途重启
- go - net/http 在 Go Playground 中不起作用
- javascript - 在任何选择选项上仅显示最后插入的记录
- python - 如何在 Jupyter Notebook 中将 python 升级到 3.8?
- node.js - 函数在同步环境中时是异步的
- java - 在浏览器中显示带有 OMML 标签的 OOXML 字符串 (Java)
- string - 如何用字母和数值标记字符串
- javascript - 带有数字和单选按钮的 Javascript/HTML 计算器不显示输出