You should override the equals () method
When you do:
coin = new Item(this, 100, 150);
You are creating a new object. So, even if you have another object with identical attributes in heap , they remain different objects, though with equal attributes.
You try to pass a new object to the remove method from the list, consequently the new object is not in the list, which maybe has in the list > different object with identical attributes .
According to the java documentation, on the remove()
method:
Remove the first occurrence of the specified element from this list, if it is present (optional operation). If this list does not contain the element, it is unchanged. More formally, remove the element with the lowest index i such that (or == null? Get (i) == null: o.equals (get (i))) (if such an element exists). Returns true if this list contains the specified element (or equivalently, if this list changed as a result of the call).
Briefly, remove()
uses the result of the equals method to tell whether objects are "equal" or not.
Therefore, you should override the equals () method to tell when different objects are considered equal.
The most modern IDEs all come with the option of overwriting the equals method automatically, so it's pretty easy to do such an operation. A possible overriding of the equals method would be as follows:
public class Item {
private Object GrupoItem;
private int width;
private int height;
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Item other = (Item) obj;
if (GrupoItem == null) {
if (other.GrupoItem != null)
return false;
} else if (!GrupoItem.equals(other.GrupoItem))
return false;
if (height != other.height)
return false;
if (width != other.width)
return false;
return true;
}
}
The code I generated automatically by Eclipse. In the equals method, the attribute equals by attribute, if all of them are considered equal, the method returns true , if at least one of the attributes is considered different, the method returns false / p>
Reference: List - Java SE 7