我有一个带有两个参数的hashmap
private HashMap<Integer, car> carList;
我已经成功地编写了允许我在HashMap中添加新值的方法。现在我想知道如何使用for循环或类似的东西来迭代Hashmap的第一个参数。我正在尝试列出所有具有相同int值(价格)的汽车;
keySet()
方法将允许您遍历映射键…
for(Integer price: carList.keySet()) {
// something
}
这样做:
for(Integer price: carList.keySet()) {
car myCar = carList.get(price);
}
可以使用KeySet()方法
From the docs:
返回映射中包含的键的Set视图。集合由映射支持,因此对映射的更改反映在集合中,反之亦然。如果在对set进行迭代时修改map(通过迭代器自己的remove操作除外),则迭代的结果是未定义的。set支持移除元素,即通过Iterator从map中移除对应的映射。删除组。remove, removeAll, retainAll和clear操作。它不支持add或addAll操作。
.
我正在尝试列出所有具有相同int值(价格)的汽车;
以价格为关键是错误的设计。你可以有一个range对象作为Key。
通过键(在您的示例中是Integer
)从映射中检索值如下:
carList.get(<your price>) --> this will get your the value(s) for this price
要遍历所有价格,可以这样做:
for(Integer price: carList.keySet()) {
.. your work
}
首先,将变量名更改为carMap。现在,您可以使用以下命令之一:
for(Integer price: carMap.keySet()) {
// something related to key.
}
或:
for(Entry<Integer,car> entry: carMap.entrySet()) {
car c = entry.getValue();
Integer ket = entry.getKey();
// something related to key and value.
}
但是,如果键是price,并且每个price持有一辆汽车,则不可能有两辆具有相同价格的汽车。您可能需要使用:
Map<Integer, List<car>>