Lets say I have an ArrayList of a class of objects. How would I be able to do erase it from within the class. Something like
ArrayList<newClass> newClassList = new ArrayList<newClass>();
newClassList.add(newClass());
class newClass {
float x, y;
void getInfo(float x_, float y_) { x = x_; y = y_; }
void erase() {
//here comes the line that erases the object.
}
}
I know it could be done by comparing itself to all the other objects in the array, but still.
Essentially I want a function that erases the object from the ArrayList.
Hi,
First of all, when you say erase in reality it’s the garbage collector that does it automatically in Java. In lower level languages like C, you can explicitly delete some piece of memory that was previously allocated.
So in this case, you rather remove the object from the array and then later it’s going to be free by the garbage collector.
Now if you want to do this inside a method, you need to tell the method from which ArrayList you want to remove it so pass it as argument :
class NewClass {
void eraseFrom(ArrayList<NewClass> array) {
array.remove(this);
}
}
Few notes here :
-
Always use PascalCase for class names in Java (see the conventions )
-
It’s better to choose method names that actually describe what they do (so erase from something…)
-
It’s using the ArrayList.remove(Object o) method to remove an object from the array. It does that :
More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i)))
It’s using the Object.equals(Object o)
method of the object which return true if true if both of the objects are considered equals. The word considered is important here because by default the equals method on every object does that :
The default implementation provided by the JDK is based on memory location — two objects are equal if and only if they are stored in the same memory address. (from here )
But most of the time, you need to implement your own equals
function inside your class in order to check the properties individually (check this link )
Anyway for me it’s more clear to do this the other way around :
ArrayList<NewClass> newClassList = new ArrayList<NewClass>();
NewClass instance = new NewClass();
newClassList.add(instance);
// Do stuff...
newClassList.remove(instance);
2 Likes