2

I was thinking of doing it like this, but I'm not sure if the reference temp is assigned will still be valid after removal.

public Box removeBox(int index)
{
Box temp=getBoxes().get(index);//ArrayList.get
getBoxes().remove(index);
return temp;
}
1
  • Your code is correct. But, the Louis Wasserman answer is more clean. As advice, read the APIs to optimize the codes, some functions in Java can be amazing when you know well how they work. Commented Apr 24, 2012 at 16:36

5 Answers 5

9

That's fine, although return getBoxes().remove(index) would do the same thing in a single line.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes it is a valid way of doing it. Java works with values, not references.

Comments

0

List.remove() doesn't invalidate the removed object.

Removing any element from any Collection doesn't invalidate it.

Comments

0

Yes, the reference will still be valid, as there already exists a reference to it (the temp variable you just defined). The JVM's garbage collector will take care of all dereferenced objects when it runs. See this link for more information: How Garbage Collection works in Java, specially When an Object becomes Eligible for Garbage Collection.

ArrayList#remove returns the removed element, if any, so you could also just do return getBoxes().remove(index).

Comments

0

you are going great , The reference will be valid

Lets take an example

A---------Object

B---------Object

A and B both are references of Object .

Now, say the reference B is invalidated

A---------Object

B--|-|-|-|--|-|-Object (Invalidated)

the reference A still remains intact.

Thanks Abhi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.