user3277779
user3277779

Reputation: 71

TreeMap using a string key and an arraylist

I am brand new to using collections, so I am confused on how to do this. I am trying to use a TreeMap to hold a word as the key and then an ArrayList to hold one or more definitions for the word.

public class Dict {
    Map<String, ArrayList<String>> dic = new TreeMap<String, ArrayList<String>>();

    public void AddCmd(String word, String def) {
        System.out.println("Add Cmd " + word);
        if(dic.get(word)==null){
            dic.put(word, new ArrayList.add(def));      
        }
    }
}

I am getting an error on "new ArrayList.add(def)". I thought this was the correct way to do this, but I am obviously wrong. Does anyone have any ideas as to what I am doing wrong?

Upvotes: 1

Views: 9519

Answers (4)

Karibasappa G C
Karibasappa G C

Reputation: 2732

dic.put(word, new ArrayList.add(def)); is the culprit. since you have declared map to take Arraylist of string as a value. the value to pass for map must be Arraylist of string.

but this line is adding a value as new ArrayList.add(def) since you are trying to create a list and adding element , add method returns boolean -> true if it can add false if it fails.

so it means value to the map is going as a boolean not as arraylist which is against the map declaration. so use code as below

ArrayList<String> listOfString = dic.get(word);
if (listOfString == null) {
    listOfString = new ArrayList<String>();
listOfString .add(def);
}
dic.put(word, listOfString );

Upvotes: 1

Dan Harms
Dan Harms

Reputation: 4840

You are not actually creating a new ArrayList. Try this:

ArrayList<String> newDef = new ArrayList<String();
newDef.add(def);
dic.put(word, newDef); 

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Calling ArrayList#add returns a boolean which is not the desired value for your Map, thus getting the compiler error.

You need to insert the ArrayList and then add the element. Your code should look like this:

ArrayList<String> definitions = dic.get(word);
if (definitions == null) {
    definitions = new ArrayList<String>();
    dic.put(word, definitions);
}
definitions.add(def);

Upvotes: 1

merlin2011
merlin2011

Reputation: 75565

You have to break it up, because add does not return the original ArrayList:

ArrayList<String>> NewList = new ArrayList<String>();
NewList.add(def);
dic.put(word, NewList);

Upvotes: 0

Related Questions