可以使用以下代碼來聲明:
Map<String, List<? extends Object>> objectsMap = new HashMap<String, List<? extends Object>>();
一個例子是如下:
MapTest類==>
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類==>
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;
}
}
自行車類==>
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;
}
}
您是否嘗試過仿製藥?像MyList一樣使用泛型,其中每次T可以取代汽車,自行車等...只是問題是你必須自己實現它,因爲你將實現List接口。 –