简体   繁体   English

数组列表 <Item> (其中Item是内部类)添加错误

[英]ArrayList<Item> (where Item is inner class) adding wrong

I have a class called Bag2 and it has inner class called Item. 我有一个名为Bag2的类,它有一个名为Item的内部类。 Bag2 has variable ArrayList aList and function called "add". Bag2具有变量ArrayList aList和称为“ add”的函数。 It's adding wrong by repeat adding duplicate value. 通过重复添加重复值来添加错误。

Here is my code: 这是我的代码:

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
            }
        }
    }

}


}

And here is my test : 这是我的测试:

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));
    }

}
}

and output: 并输出:

A list contains : A : 3 B : 1 C : 1 D : 1 A : 1 F : 1 B : 1 E : 1 A : 1 列表包含:A:3 B:1 C:1 D:1 A:1 F:1 B:1 E:1 A:1

Your add function is broken because it can trigger the statement if (item.compareTo(aList.get(i))==0) for one i value and still add it for another value. 您的add函数已损坏,因为它可以触发一个iif (item.compareTo(aList.get(i))==0)的语句if (item.compareTo(aList.get(i))==0)而仍将其添加到另一个值。 While there are more elegant and robust solutions for you program including overriding equals() and hashCode() and using a Set instead of a list, that would result in a generic bag implementation and I posted the shortest fix for your problem. 尽管有一些更优雅,更健壮的解决方案为您提供编程方法,包括覆盖equals()hashCode()以及使用Set而不是列表,但这将导致通用bag实施,我针对您的问题发布了最短的解决方案。

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);}
    }
}

Let's say you add the following items : A,B,C 假设您添加了以下项目: A,B,C

now your list is : A:1, B:1, C:1 现在您的列表是: A:1,B:1,C:1

In your add logic you check if the current item is the same one, otherwise you add the item. 在添加逻辑中,检查当前项目是否相同;否则,添加项目。 So if we now try to add item C again your list will look like this: A:1, B:1, C:1, C:1 因此,如果我们现在再次尝试添加项目C,您的列表将如下所示: A:1,B:1,C:1,C:1

This is because you are checking item by item. 这是因为您正在逐项检查。 Before adding the new item you need to check that it does not exist in the ENTIRE list and only then add it. 在添加新项目之前,您需要检查它在整个列表中是否不存在,然后添加它。 (eg When adding C to the above list the first loop iteration ( i=0 ) will execute the code in the else block since C and A are different and C will be added although it does exist in the list) (例如当添加C到上述列表中的第一循环迭代( i=0 )将在其他块执行的代码,因为CA是不同的和C将被添加尽管它在列表中存在)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM