0

Test是我的单独类,它有两个字段StringFloat类型,我将这个类与列表集合一起使用,最终将作为值填充到HashMap.

但是,当我尝试使用键和 List 对象(值)将 Map 填充到地图中时,Java 似乎不接受它,因为它不是有效的语法:

ArrayList <Test> list = new ArrayList <Test> ();

Map<Integer, ArrayList <Test>> mp = new HashMap<Integer, ArrayList <Test>>();  

list.add(new Telephone ( 0.9 , "A"));
list.add(new Telephone(5.1 , "A"));

mp.put(0,list.get(0)); // this Does Not work :(, it should work

输出:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The method put(Integer, ArrayList<Telephone>) in the type  
   Map<Integer,ArrayList<Telephone>> is not applicable for the arguments 
   (int,   Telephone) at Main.main(Main.java:64)
4

3 回答 3

2

您的地图接受 Integer 作为键和 Test 的 ArrayList 作为值。但是,您尝试放置 Telephone 对象,而不是 Test 对象的 arrayList。您的 IDE 清楚地说明了这一点。

Map<Integer,ArrayList<Telephone>> is not applicable for the arguments 
   (int,   Telephone) at Main.main(Main.java:64)
于 2013-01-26T18:25:58.303 回答
2

按照您在上面的评论和问题中提出的要求,我认为您需要以下语法来声明 Map:

Map<Integer,Test> mp = new HashMap<Integer,Test>();

编辑

好的,这里是编辑:

ArrayList<Test> list = new ArrayList<Test>();
Map<Integer,ArrayList<Test>> mp = new HashMap<Integer,ArrayList<Test>>();
list.add(new Test(0.1,"A"));
list.add(new Test(0.2,"B"));
mp.put(1,list);

如果您再次想在键 1 上放置更多 Test 对象,请执行以下操作:

List<Test> value = mp.get(1);
value.add(0.3,"c");
value.add(0.5,"E");

mp.put(1,value);
于 2013-01-26T18:48:01.823 回答
1

您映射只能接受List对象作为值,而您试图将简单的Telephone对象放在那里。

于 2013-01-26T18:23:28.397 回答