如何将(String,List <myobject>)放入Map <string,list <object =“”>&gt; </string,> </myobject>

时间:2013-11-15 15:55:28

标签: java list map casting

我有<String, Lists>的地图,但条目包含不同类型的列表。

因此,第一个条目可能是put("cars", List<Cars>),第二个条目可能是put("bikes", List<Bikes>)

我声明了Map<String, List<Object>> myVehicles来举行此活动。当我尝试将条目放入:

List<Bikes> bikes = ...
myVehicles.put("bikes", (List<Object>)bikes);

我收到错误,“无法从列表转换为列表”。我需要做什么?感谢。

2 个答案:

答案 0 :(得分:1)

您应该将地图声明为:

Map<String, List<? extends Object>> myVehicles = 
                                new HashMap<String, List<? extends Object>>();

Map<String, List<Object>>不起作用,因为您无法在需要List<Bikes>的位置添加List<Object>,因为泛型类型不变List<Bikes>不是List<Object>的子类,但可以由List<? extends Object>捕获。

答案 1 :(得分:0)

您可以使用以下代码声明:

Map<String, List<? extends Object>> objectsMap = new HashMap<String, List<? extends Object>>(); 

一个例子如下:

MapTest class ==&gt;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MapTest {

public static void main(String[] args) {

    Map<String, List<? extends Object>> objectsMap = new HashMap<String, List<? extends Object>>();

    //Put String List into Map
    objectsMap.put("String", Arrays.asList("Hello","Java"));


    //Put Object List into Map
    objectsMap.put("Object", Arrays.asList(new Object(),new Object()));

    //Put Car List into Map
    objectsMap.put("Car", Arrays.asList(new Car("Band1"),new Car("Band2")));

    //Put Bike List into Map
    objectsMap.put("Bike", Arrays.asList(new Bike("Band1"),new Bike("Band2")));

}
}

Car class ==&gt;

public class Car {

private String band;

public String getBand() {
    return band;
}

public Car(String band) {
    super();
    this.band = band;
}

public void setBand(String band) {
    this.band = band;
}
}

自行车课程==&gt;

public class Bike {

private String band;

public String getBand() {
    return band;
}

public void setBand(String band) {
    this.band = band;
}

public Bike(String band) {
    super();
    this.band = band;
}

}