I have a class called Bag2 and it has inner class called Item. Bag2 has variable ArrayList aList and function called "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
Itemastaticclass? I strongly recommend using a debugger and go step by step through youraddmethod. You will find out what’s happening very soon.