Reputation: 9
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>>());
Upvotes: 0
Views: 159
Reputation: 3797
ArrayList
in new ArrayList<Integer>>()
(with contains a syntax error as well - a >
too many), but never add number
to it.add
on a HashMap
, which doesn't have this method. For maps, it is called put
.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);
}
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.
Upvotes: 2
Reputation: 426
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
Upvotes: 2
Reputation: 2191
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.
Upvotes: 4