[英]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>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.