Reputation: 95
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?
Upvotes: 1
Views: 255
Reputation: 86774
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.
Upvotes: 3
Reputation: 10370
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.
Upvotes: 2
Reputation:
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.
Upvotes: 0