[英]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.
我正在尝试使用TreeMap来容纳一个单词作为关键字,然后使用ArrayList来容纳该单词的一个或多个定义。
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)
". 我在“
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?
有人对我在做什么错有任何想法吗?
Calling ArrayList#add
returns a boolean
which is not the desired value for your Map
, thus getting the compiler error. 调用
ArrayList#add
返回一个boolean
,该boolean
不是Map
所需的值,从而导致编译器错误。
You need to insert the ArrayList
and then add the element. 您需要插入
ArrayList
,然后添加元素。 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);
dic.put(word, new ArrayList.add(def)); dic.put(word,new ArrayList.add(def)); is the culprit.
是罪魁祸首。 since you have declared map to take Arraylist of string as a value.
因为您已声明map以字符串Arraylist作为值。 the value to pass for map must be Arraylist of string.
要传递给map的值必须是字符串的Arraylist。
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. 但是此行将值添加为新的ArrayList.add(def),因为您尝试创建列表并添加element,add方法返回boolean-> true,如果失败则可以添加false。
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 );
You have to break it up, because add
does not return the original ArrayList: 您必须将其分解,因为
add
不会返回原始的ArrayList:
ArrayList<String>> NewList = new ArrayList<String>();
NewList.add(def);
dic.put(word, NewList);
You are not actually creating a new ArrayList. 您实际上并不是在创建新的ArrayList。 Try this:
尝试这个:
ArrayList<String> newDef = new ArrayList<String();
newDef.add(def);
dic.put(word, newDef);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.