我需要一个ArrayList<Coin>
选择独特的元素并添加到另一个 ArrayList<LineItem>
。 LineItem 在第一个列表中包含硬币和匹配该硬币的数量。
我的代码可以工作,但不正确,我不知道如何规避此限制?
这是检查输出:
// it's list of coin's element
LineItem [quantity=1, theCoin=Coin[value=0.5,name=half dollar]]
LineItem [quantity=1, theCoin=Coin[value=0.25,name=quantity dollar]]
LineItem [quantity=1, theCoin=Coin[value=0.25,name=quantity dollar]]
LineItem [quantity=1, theCoin=Coin[value=0.5,name=half dollar]]
LineItem [quantity=1, theCoin=Coin[value=0.5,name=half dollar]]
// list of LineItem's element
[
LineItem [quantity=2, theCoin=Coin[value=0.5,name=half dollar]],
LineItem [quantity=2, theCoin=Coin[value=0.25,name=quantity dollar]],
LineItem [quantity=1, theCoin=Coin[value=0.5,name=half dollar]]
]
列表LineItem
元素应仅包含具有唯一 name
的元素。
如果名称进入列表,它应该只更新该元素的数量。
(我们只有两个元素:硬币半美元和数量美元。LineItem 列表必须只有这两个硬币名称,并且将数量匹配到硬币列表中)
代码:
private static ArrayList<LineItem> createItems(ArrayList<Coin> coins) {
ArrayList<LineItem> itemsList = new ArrayList<LineItem>();
for (Coin aCoin : coins) {
LineItem anItem = new LineItem(aCoin, 1);
System.out.println(anItem.toString()); // print every Coin element
if (!itemsList.contains(anItem)) {
itemsList.add(anItem);
} else {
int i = 0;
boolean done = false;
while (!done & i <= itemsList.size()) {
Coin currentCoin = itemsList.get(i).getCoin();
int currentQuantity = itemsList.get(i).getQuantity();
if (currentCoin.equals(aCoin)) {
itemsList.get(i).setQuantity(currentQuantity + 1);
done = true;
} else {
i++;
}
}
}
}
System.out.println("\n" + itemsList.toString()); // print final LineItem's list
return itemsList;
}
它将最后一个元素添加到 itemsList
因为这个列表不包含数量== 1的元素。但是这个列表有相同的 Coin
值。
如何解决这个问题?
最佳答案
我认为问题出在 LineItem
的 equals
中 - 它不仅检查 Coin
,还检查数量
因此,当您调用 List.contains
时,如果您处理了两个相同的硬币,它会返回 false
。
代码的固定版本可能如下所示
for (Coin aCoin : coins) {
boolean done = false;
for (Iterator<LineItem> it = itemList.iterator();it.hasNext() && !done) {
LineItem currentItem = it.next()
Coin currentCoin = currentItem.getCoin();
int currentQuantity = currentItem.getQuantity();
if (currentCoin.equals(aCoin)) {
currentItem.setQuantity(currentQuantity + 1);
done = true;
}
}
if(!done) {
LineItem anItem = new LineItem(aCoin, 1);
itemsList.add(anItem);
}
}
但在这种情况下我更喜欢使用 map
添加了 map 代码
Map<Coin, LineItem> map = new HashMap<Coin, LineItem>();
for (Coin aCoin : coins) {
LineItem anItem = map.get(aCoin);
if(anItem == null) {
map.put(aCoin, new LineItem(aCoin, 1));
} else {
anItem.setQuantity(anItem.getQuantity()+1);
}
}
itemsList.addAll(map.values());
但是如果你不使用Coin#hashCode
关于java - 从一个 ArrayList 提取并修改到另一个 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18622990/