Reputation: 123
I was able to remove an Integer from a List and store it in a variable. However, I am having troubles doing it with String. Is there a way to remove a string in a List and store it? The code below shows how I can do it with Integers:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
Integer removedItem = list.remove(3);
I did the same but this time with String but doesnt work:
List<String> list = new ArrayList<String>();
list.add("Milk");
list.add("Eggs");
list.add("Butter");
String removedItem = list.remove("Butter");
Is it possible to store something that is removed (String) ? I would appreciate any help! Thanks!
Upvotes: 0
Views: 559
Reputation: 11483
You're confusing List#remove(index)
and List#remove(Object)
. The first example isn't actually removing the number 3
, but the 4th (index 3) item in your list and returning what object it was. If you did list.remove(3)
with your String list, you would get the 4th String object back. Additionally, if you already know the string you're removing, why do you need to store it again?:
String toRemove = "Butter";
list.remove(toRemove); //we already know it's "Butter"
Upvotes: 5
Reputation: 6391
There are actually two different methods you used.
Collection.remove(Object o) tries to remove an object and returns true if removed something (false otherwise). You use this approach in the example with List<String>
and can do the same with List<Integer>
if you replace Integer removedItem = list.remove(3);
with Integer removedItem = list.remove(new Integer(3));
List.remove(int index) removes an element by its index in List and returns removed element. In your first example in Integer removedItem = list.remove(3);
you actually used that method because you've passed an int as the argument instead of object (in that case it would be Integer).
Remember that indexes in java collections start at 0, so you'll get NullPointerException while trying to execute your first example.
Upvotes: 1