You must override the equals method()
When you do:
coin = new Item(this, 100, 150);
you are creating a new object. So, as much as you have another object with identical attributes in heap , they remain different objects, however with equal attributes.
You try to pass an object new for the method to remove from the list, hence the new object is not on the list, what you might have on the list is a different object with identical attributes.
According to the java documentation, about the method remove()
:
Removes 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, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).
Briefly, the remove()
uses the result of the equals method to tell whether objects are "equal" or not.
Therefore, you must override the equals() method to tell when different objects are considered equal.
The most modern Ides all come with the override option of the equals method automatically, so it is quite easy to do such an operation. A possible superscript 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 automatically generated by Eclipse. In it the equals method compares attribute 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.
Reference: List - Java SE 7
If you want the English version of SO go here: Stackoverflow. This is the Portuguese version and Even if you Ask there, you still have to provide more information or other Parts of your code. As the error Might not be in this part.
– Mansueli
I thought it was in the English version, I’m sorry. I think the problem is with the rectangle that remains at that location and then continues to intercept repeatedly but I see no way to remove the rectangle. What other parts of the code should show?
– user9165
Could post the declaration of the Rectangle class?
– Wakim
The Rectangle class is a Java import, I made no changes to it. import java.awt.Rectangle;
– user9165