Reputation: 257
I have a List<Integer> nums = new ArrayList<>()
and I do this:
for(int i=1;i<=9;i++)
nums.add(i);
Here I have the list {1,2,3,4,5,6,7,8,9} .
What i want to do is given another List, if I receive the number 8, I want to remove the 8 from nums list. I'm doing that like this : shuffle.remove(genNumber-1);
The problem is If i already removed 3 numbers ({1,2,3} for instances) and the genNumber I receive is 9 it will try to remove at the index 9-1 = 8 which doesn't exist already because the current list is {4,5,6,7,8,9} <-> index=6, therefore didn't remove the number that i wanted that was the 9.
Thanks guys
Upvotes: 1
Views: 248
Reputation: 31
nums.remove((Integer)9 ); should fix it; You could be passing an int into it, so it assumes you're calling the remove by index method remove(int index). By explicitly specifying 9 as an object you are using the remove(Object o) method of a list. References to documentation for list
Upvotes: 0
Reputation: 1913
Do not use an int, as that is going to remove whatever is at the index, not the matching object. You will need to use something of type Integer, which has a constructor that takes in an int and should be a quick fix.
int toRemove = 9;
nums.remove(new Integer(toRemove));
Upvotes: 1
Reputation: 2686
This question is strangely worded.
So the two solutions could be as followed.
1) If you want to remove by index then you are going to have to add some logic to how you generate your numbers to never exceed the list.size()
2) If you want to remove by value then you can just iterate through the list and remove the value you want to. Now you have to figure out what you want to do with that extra space in the array. (lets say you never deal with negative values you can add a "placeholder" of -1)
for(int i = 0; i < list.size(); i++){
if(list[i] == toMatchValue) list[i] = -1;
}
Upvotes: 0
Reputation: 195
Pass in an Integer
rather than an int
. This will ensure that List#remove(Object)
is used rather than List#remove(int)
.
Upvotes: 2