ArrayList <item>(其中Item是内部类)添加了错误的</item>

时间:2014-09-27 15:17:37

标签: java class arraylist

我有一个名为Bag2的类,它有一个名为Item的内部类。 Bag2具有变量ArrayList aList和函数名为&#34; add&#34;。它通过重复添加重复值来添加错误。

这是我的代码:

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 B:1 C:1 D:1 答:1 F:1 B:1 E:1 答:1

2 个答案:

答案 0 :(得分: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);}
    }
}

答案 1 :(得分:0)

假设您添加以下项目: A,B,C

现在您的列表是: A:1,B:1,C:1

在添加逻辑中,检查当前项目是否相同,否则添加项目。因此,如果我们现在尝试再次添加项目C,您的列表将如下所示: A:1,B:1,C:1,C:1

这是因为您要逐项检查。在添加新项目之前,您需要检查它是否在整个列表中不存在,然后才添加它。 (例如,当将 C 添加到上面的列表时,第一个循环迭代(i=0)将执行else块中的代码,因为 C A < / strong>是不同的,并且 C 将被添加,尽管它确实存在于列表中)