简体   繁体   中英

JAVA: What does it mean to map string keys?

I have been given this assignment where the instructor has asked us to

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

My question is what does mapping a string to a Q value mean? Im sorry if this is a simple question, but im very new to this.

Also, im not sure if it will change the answer or not, but in the code we can not use any Java Collections library so i have to code this from scratch

So First point create HashMap with initial storage 7, below line creates HashMap with initial capacity 7 which accepts String type key and String type value

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

Example to add key value to HashMap

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

According to you need to create HashMap with String type key and Q type value, so i believe Q must be class or interface

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

Note: hashmap will override value for duplicate keys

If you don't want to use Collections for this, then you should create CustomHashMap with implementation

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];
}

In the above code by default initial capacity is 7 HashMapCustom<String, Q> hashMapCustom = new HashMapCustom<String, Q>();

But still you need to write your own logic for put , delete , get and the methods you need. i suggest you to check this ref1 , ref2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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