简体   繁体   中英

Java hashtable bucket as an ArrayList

I want to create a HashMap where each Key could have multiple Value s. For example, the key umbrella could have value s of red, black, and green. I have heard that the buckets in a Hashtable could be LinkedList s, ArrayList s, etc. How could I implement a bucket as an ArrayList so that I would be able to add items that match the key to the end of the list?

I want to have a something like Map<Key, Value> . If the Key exists, the Value will be added to the list of current Value s.

You should use Map<K, List<V>> map = new HashMap<>();

Instead of map.put(k, v) , you will do something like this:

List<V> vs = map.get(k);
if (vs == null) {
    vs = new ArrayList<>();
    vs.add(v);
    map.put(k, vs);
} else {
    vs.add(v);
}

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