我有一个名为 Bag2 的类,它有一个名为 Item 的内部类。 Bag2 有变量 ArrayList aList 和名为“add”的函数。重复添加重复值会导致添加错误。
这是我的代码:
import java.util.ArrayList;
public class Bag2 {
public Bag2(){}; // Constructor
/**
* Inner class
*
*/
public class Item implements Comparable<Item> {
String name;
int quantity;
public Item(String name, int quantity) { // Constructor
this.name = name;
this.quantity = quantity;
}
@Override
public String toString() {
return name + " : " + quantity;
}
@Override
public int compareTo(Item o) {
return name.compareToIgnoreCase(o.name);
}
}
public ArrayList<Item> aList = new ArrayList<>();
public void add(String itemName){
Bag2 bag2 = new Bag2();
Bag2.Item item = bag2.new Item(itemName.toUpperCase(), 1);
if (aList.isEmpty()){
aList.add(item);
} else
{
for(int i = 0; i < aList.size();i++){
if (item.compareTo(aList.get(i))==0){
aList.get(i).quantity++;
}else {
aList.add(item); // Built inn add-function
break; // add one time only and the size increases
}
}
}
}
}
这是我的测试:
public class Bag2Test {
public static void main(String[] args) {
Bag2 bag = new Bag2();
Bag2.Item[] anArray =
{
bag.new Item("A", 1),
bag.new Item("B", 1),
bag.new Item("C", 1),
bag.new Item("D", 1),
bag.new Item("a", 1),
bag.new Item("F", 1),
bag.new Item("b", 1),
bag.new Item("e", 1),
bag.new Item("a", 1)
};
for (int i = 0; i<anArray.length; i++ ){
bag.add(anArray[i].name); //
}
System.out.println("\nA list contains : ");
for (int i = 0; i<bag.aList.size(); i++) {
System.out.println(bag.aList.get(i));
}
}
}
和输出:
列表包含: 答:3 乙:1 C:1 直径:1 答:1 法:1 乙:1 乙:1 答:1
最佳答案
您的add
函数已损坏,因为它可以触发语句 if (item.compareTo(aList.get(i))==0)
一个i
值并仍然将其添加为另一个值。虽然有更优雅和强大的解决方案供您编程,包括覆盖 equals()
和hashCode()
并使用 Set 而不是列表,这将导致通用包实现,我发布了针对您的问题的最短修复。
public void add(String itemName)
{
Bag2 bag2 = new Bag2();
Bag2.Item item = bag2.new Item(itemName.toUpperCase(), 1);
if (aList.isEmpty())
{
aList.add(item);
} else
{
boolean existing = false;
for(int i = 0; i < aList.size();i++)
{
if (item.compareTo(aList.get(i))==0)
{
aList.get(i).quantity++;
existing=true;
break;
}
}
if(!existing) {aList.add(item);}
}
}
关于java - ArrayList<Item> (其中 Item 是内部类)添加错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26076126/