我有以下代码,一个带有水果数组列表的 Treemap。在 removeAndAdd 函数中,我想删除 [apple,orange] 并将其添加到容器 2 的 bList 中。但显示出来的是额外的括号 []。我的方法正确吗?
public class TreeMapEx {
private TreeMap<Integer, List<String>> tMap = new TreeMap<Integer, List<String>>();
private List<String> aList = new ArrayList<String>();
private List<String> bList = new ArrayList<String>();
public static void main(String[] args) {
TreeMapEx tm = new TreeMapEx();
tm.addToTree();
tm.addToList(1);
tm.showItem(1);
tm.showItem(2);
tm.removeAndAdd(1);
tm.showItem(2);
}
private void addToTree() {
tMap.put(1, aList);
bList.add("dragonfruit");
tMap.put(2, bList);
}
private void addToList(int item) {
if (tMap.containsKey(item)) {
aList = new ArrayList<String>();
aList.add("apple");
aList.add("orange");
tMap.put(item, aList);
System.out.println(item + " added");
} else {
System.out.println(item + " not found");
}
}
private void showItem(int item){
System.out.println(item+" contain " + tMap.get(item));
}
private void removeAndAdd(int item){
if (tMap.containsKey(item) && tMap.containsValue(aList)) {
//remove everything from 1 and add to 2
aList = new ArrayList<String>();
List<String> temp;
temp = tMap.get(item);
bList.add(temp.toString());
}
}
}
Output:
1 added
1 contain [apple, orange]
2 contain [dragonfruit]
2 contain [dragonfruit, [apple, orange]]
如何移除容器 2 中 [apple, orange] 的附加支架。
对于这样的事情
1 added
1 contain [apple, orange]
2 contain [dragonfruit]
2 contain [dragonfruit,apple, orange]