1

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?

4 Answers 4

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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 );

Comments

0

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);

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.