简体   繁体   中英

Hashmap arraylist (java)

Okay, so I'm fairly new to programming so apologies if this problem is really simple, I've created an ArrayList inside my Hash Map so that I can add more than one value into my hash map.

My code looks fine (to me) but theres an error on this line "mymap.add(module, new ArrayList>());" saying ( or [ expected.

Wasted way too much time trying to figure this out so thought I'd post here. Thanks in advance for any help. Also: yes I need to do it this way and no I can't use guava MultiMap .

public class hashArray {
HashMap<String, ArrayList<Integer>> mymap = new HashMap<String, ArrayList<Integer>>();
public hashArray() {}
public void addEntryHR( String module, Integer result ) {
mymap.add(module, new ArrayList<Integer>>());

There is a typo and a bug in your line:

//         The typo is right here    v
mymap.add(mod, new ArrayList<Integer>>());

Remove one of the > and change add to put :

mymap.put(mod, new ArrayList<Integer>());

The error you get, is about the typo. Fixing that typo will give you an error about add to be an unknown method.

The problems

  • You create a new ArrayList in new ArrayList<Integer>>() (with contains a syntax error as well - a > too many), but never add number to it.
  • You are calling add on a HashMap , which doesn't have this method. For maps, it is called put .

Proposed solution

Please see the code below

Map<String, List<Integer>> myMap = new HashMap<>();

public void addEntryHR(String mod, Integer number) {
    List<Integer> numbers = new ArrayList<>();
    numbers.add(number);

    myMap.put(mod, numbers);
}

Other remarks

Use interfaces
It is advised to use the interfaces of the collections rather than the implementations. This means Map<String, String> myMap instead of HashMap<String, String> myMap and List<Integer> instead of ArrayList<Integer> .
Why do this? Because this allows you to be flexible in the collections you use and reduce maintenance effort. Say you change your mind and want to use LinkedList instead of ArrayList , then you just have to change one new ArrayList<>() to new LinkedList<>() instead of all the ArrayList variables used throughout the code.

You need to first get the list out from map object like below-

ArrayList<Integer> list = mymap.get(mod);

if (list==null){
    //then create new ArrayList object and assign to list
    list=new ArrayList<Integer>();
 }
  list.add(number);  //adding new number to the list
  mymap.put(mod,list); //storing in map

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