0

如何从 HashMap 打印 ArrayList?

Map<String, ArrayList<Car>> cars = new HashMap<String, ArrayList<Car>>;

ArrayList<Car> carList = cars.get("bmw");

    for (int i = 0; i < carList.size(); i++) {
        System.out.println(carList.get(i));
    }

代码导致:

java.lang.NullPointerException

尽管“bmw”键存在并已填充。

4

5 回答 5

1
Iterator<String> itr = carList.iterator();
    while (itr.hasNext()) {
      String element = itr.next();
      System.out.print(element + " ");
    }

Inoder to do this carList should not be a null value.
To add values to ArrayList you can use

carList.add("Some value");
于 2012-09-02T04:32:45.423 回答
1

尝试添加一个

System.out.println(cars.get("bmw"));

检查并查看其中的确切内容(在地图和汽车的 ArrayList 中)。

于 2012-09-02T04:27:16.280 回答
0

遍历列表的最简单方法是使用 foreach:

ArrayList<Car> carList = cars.get("bmw");  
for (Car car : carList) {
    System.out.println(car.getYourValueToPrint());
}
于 2012-09-02T10:10:24.457 回答
0

遍历 ArrayList 最安全的方法是通过增强每个循环,从而为您省去 a 的痛苦NullPointerException

ArrayList<Car> carList = cars.get("bmw");
for(Car car: carList){
    car.doAnyOpertation();
    System.out.println(car.getAnyValue());
}
于 2012-09-02T10:43:19.807 回答
0
ArrayList<Car> carList = cars.get("bmw");
for(Car car: carList){
    car.doAnyOpertation();
    System.out.println(car.getAnyValue());
}

即使在这种情况下,如果 carList 为空,则
for(Car car: carList)与 throw NPE一致

于 2012-09-03T07:12:11.170 回答