1

Let's say you have two lists declared:

ArrayList listA = new ArrayList();
ArrayList<Book> listB = new ArrayList<Book>();

And then you have these statements:

Object obj = listA.remove(2);
Book bk = listB.remove(2);
String str = listA.remove(1);

Assuming there is an object in each of the specified locations, why would you want to assign these methods to a variable, and what would be consequences of it? I have read this chapter like three times, and I still don't understand this. What am I missing?

3 Answers 3

3

The remove(int) method removes an object from the list and returns the object that was removed. Removing an object is not the same as deleting it... you may have a use case where you want to remove an object but still want to do something with it. If you really don't want the object after it's removed, just don't assign it, as in

list.remove(3)

This will remove the object at offset (3) and not retain a reference to it. If there are no other references, it will eventually get garbage-collected.

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

Comments

2

Looking at the three statements:

The first one Object obj = listA.remove(2) is using a raw type. That definition holds Object. Everything inherits from Object, so it can really hold anything. That can lead to problems. Look at this post to see why that is not desirable.

The second one is strongly typed. You can only remove items and assign it to the type from the definition (in ArrayList<Book>, it must match Book). That's a way for the java compiler to check your types to make sure you're working with all of the same types. If you mismatch, I believe it is a compiler error.

The third one demonstrates why the first item is a problem. Read that post and it will tell you why.

2 Comments

you put a kitty in, and when you want to take it out, it's... an object. Depressing :-(
Ohhhh, I get it. There are compilation errors when you try to assign the item being removed to a variable with a different type. How did I not realize that before? Also, that post was very helpful. Thanks!
0

When an ArrayList uses the #remove(Object obj) method, it returns true if it was removed successfully, or false if it was not removed.

Edit: just noticed I used the Object parameter there. Besides that the index parameter method, it returns the value that is removed.

This can be useful for transferring from 1 list to another, or sometimes even in recursive methods.

5 Comments

I thought the remove function returned the item that was removed at that position.
He is caling remove(int) not remove(Object).
@Legend: OP is passing the index to remove method not object.

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.