繁体   English   中英

JAVA:映射字符串键是什么意思?

[英]JAVA: What does it mean to map string keys?

老师要求我们给我这份作业

    //Create a hash table where the initial storage
   //is 7 and string keys can be mapped to Q values

我的问题是将字符串映射到Q值是什么意思? 我很抱歉,如果这是一个简单的问题,但我对此很陌生。

另外,我不确定是否会更改答案,但是在代码中我们不能使用任何Java Collections库,因此我必须从头开始编写代码

因此,首先要创建具有初始存储7的HashMap ,在下面的行中创建具有初始容量7的HashMap ,该存储可以接受String类型的键和String类型的值

HashMap<String, String> map = new HashMap<String, String>(7);

HashMap添加键值的示例

map.put("hello", "world");

根据您需要使用String类型的键和Q类型的值创建HashMap ,所以我相信Q必须是类或接口

HashMap<String, Q> map = new HashMap<String, Q>(7);

注意:哈希映射将覆盖重复键的值

如果您不想为此使用Collections, CustomHashMap使用实现创建CustomHashMap

class HashMapCustom<K, V> {

 private Entry<K,V>[] table;   //Array of Entry.
 private int capacity= 7;  //Initial capacity of HashMap

 static class Entry<K, V> {
     K key;
     V value;
     Entry<K,V> next;

     public Entry(K key, V value, Entry<K,V> next){
         this.key = key;
         this.value = value;
         this.next = next;
     }
 }

public HashMapCustom(){
   table = new Entry[capacity];
}

在上面的代码中,默认初始容量为7 HashMapCustom<String, Q> hashMapCustom = new HashMapCustom<String, Q>();

但是仍然需要为putdeleteget和所需的方法编写自己的逻辑。 我建议你检查一下ref1ref2

暂无
暂无

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

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