【问题标题】:JAVA: What does it mean to map string keys?JAVA:映射字符串键是什么意思?
【发布时间】:2018-10-04 04:22:56
【问题描述】:

老师要求我完成的任务

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

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

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

【问题讨论】:

    标签: java hashmap mapping hashtable


    【解决方案1】:

    所以首先创建HashMap,初始存储为7,下面的行创建HashMap,初始容量为7,接受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);
    

    注意:hashmap 会覆盖重复键的值

    如果您不想为此使用集合,那么您应该创建 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];
    }
    

    上述代码中默认初始容量为7HashMapCustom&lt;String, Q&gt; hashMapCustom = new HashMapCustom&lt;String, Q&gt;();

    但是您仍然需要为putdeleteget 和您需要的方法编写自己的逻辑。我建议你检查这个ref1,ref2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 2018-05-01
      • 2012-05-25
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      相关资源
      最近更新 更多