向Map <string,arraylist <string =“”>&gt;添加值时出错

时间:2015-10-10 23:17:13

标签: java dictionary arraylist hashmap

我收到了错误

error: incompatible types: String cannot be converted to ArrayList<String>
         crazyMap.put(company, day);

当我运行此代码时

Map<String, ArrayList<String>> crazyMap = new HashMap<String, ArrayList<String>>();
String company = "myCompany";
String day = "Monday";
crazyMap.put(company, day);

如何格式化'day'参数以满足类型错误?

2 个答案:

答案 0 :(得分:0)

您对数据结构的目标是什么?

madMap应该存储一个映射到一天的公司,就像你试图在上面添加一样吗?如果是这样,请尝试:

Map<String, String> crazyMap = new HashMap<String, String>();
String company = "myCompany";
String day = "Monday";
crazyMap.put(company, day);

或者您是否希望crazyMap拥有一个映射到多天的公司?像这样:

Map<String, Collection<String>> crazyMap = new HashMap<String, Collection<String>>();
Collection<String> days = new ArrayList<String>();
days.add("Monday");
crazyMap.put("myCompany", days);

答案 1 :(得分:0)

我建议使用专为多个值设计的现有类型,而不是自己使用@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_player_bio, container, false); ... Bundle arguments = getArguments(); Bio bio = arguments.getParcelable("bio"); ... return view; } Guavas Multimap(explanation; JavaDoc)。

而不是这样做:

ArrayList

你可以这样做:

Map<String, ArrayList<String>> crazyMap = new HashMap<>();
crazyMap.put("myCompany", new ArrayList<>(Arrays.asList("Monday")));

这也避免了丑陋的东西,如:

Multimap<String, String> crazyMap = ArrayListMultimap.create();
crazyMap.put("myCompany", "Monday");

如果它不存在,Guava会为您创建集合。请致电:

ArrayList<String> items; 
if (crazyMap.containsKey("myCompany")) {
    items = crazyMap.get("myCompany");
} else {
    items = new ArrayList<>();
}
items.add("Tuesday");
crazyMap.put("myCompany", items);

一切都已完成。

一个缺点是,使用的接口是crazyMap.put("myCompany", "Tuesday"); ,它不会扩展MultiMap。这意味着您必须将变量类型“弱化”为Map,例如:

MultiMap

而不是:

public void someMethod(MultiMap<K, V> multimap)

在此处详细了解差异:"Multimap Is Not A Map"

您可以在maven repository上找到最新版本的Guava。