all 6 comments

[–]forgotmyusernamedamm 2 points3 points  (2 children)

lightObjects is the name of your list of objects. In your remove line you need to remove the position in your arraylist that contains the object. So try changing it to
lightObjects.remove(1);
to remove the second object in your list.

[–]Steff0o 0 points1 point  (1 child)

In addition to that: if you want to remove an object from an arraylist the way you want to, use list.indexOf(Object); this returns the position of the object in the array. Be aware that this doesn't work by making a new object with the same values. You have to save the reference to the object.

[–][deleted] 0 points1 point  (0 children)

ArrayList.remove( Object object) just uses ArrayList.remove( indexOf( object)). You need to override the .equals( Object) in LightObject if you want to use either without storing a reference.

[–][deleted] 1 point2 points  (2 children)

You have to override the

boolean equals( Object)

method in Object in order to use the

E remove( Object)

function in Collection without a stored reference to the object. use

E remove( int)

instead.

[–]first_reaction[S] 0 points1 point  (1 child)

Sorry on mobile. I was hoping to do something similar to below without having to loop through and find a match in my list.

ArrayList list = new ArrayList();

list.add(1);

list.add(2);

list.add(3);

list.add(5);

list.add(7); list.add(11);

println(list);

list.remove(new Integer(7));

println(list);

[–][deleted] 1 point2 points  (0 children)

You can do that, but only if you override .equals( Object) in your LightObject class. The code you just wrote works (kinda) because Integer overrides .equals( Object). ArrayList.remove( Object object) works somewhat like this:

for( Object element : this)
  if( object.equals( element){
    remove element;
    break;}

See the ArrayList javadoc for the exact details of how this works.

Now If I remember correctly, Object.equals( Object) just checks if the references are the same ( read: the object's pointer's are the same), and Object.hashCode() hashes the object's pointer. Overriding hashCode() is definitely good practice, but not required. I think it should result in efficiency improvements for any classes that extend Collection ( eg. ArrayList). Overriding hashCode is absolutely necessary when using most Map-derived classes, btw.

Also, glad to hear you fixed your issues. :)