簡體   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