Reputation: 119
I have an ArrayList of Strings and I'm trying to remove the odd elements of the ArrayList, i.e. list.remove(1), list.remove(3), list.remove(5) etc.
This is the code I'm attempting to use which throws up an IllegalStateException error:
int i = 0;
for (Iterator<String> it = words.iterator(); it.hasNext(); )
{
if (i % 2 != 0 && it.hasNext())
{
it.remove();
}
i++;
}
Is there a better (working) way to do this?
Upvotes: 4
Views: 12561
Reputation: 50229
You can try something like this to remove every second element starting from words[1]
. No need to check whether the index is odd, when we remove an element we can just increment i
and that will be the next odd number.
int i = 1;
while (i < words.size()) {
words.remove(i++);
}
Upvotes: 2
Reputation:
public static List<Integer> removeImpairElements(List<Integer> integers){
int j = 0;
for(int i = 0 ; i < integers.size(); i++){
if( i % 2 == 0){
integers.set(j, integers.get(i));
j++;
}
}
int half = integers.size()%2==0 ? integers.size()/2 : integers.size()/2 + 1;
integers.subList(half , integers.size()).clear();
return integers;
}
Upvotes: 0
Reputation: 425178
I wouldn't use an iterator, because you don't need to examine the elements. Just use List.remove(index)
:
for (int i = words.size() - 1; i >=0; i--) {
if (i % 2 == 1) {
words.remove(i);
{
}
Note that you must count down, not up with this approach because removing an element shuffles e everything after to the left
If your list is immutable (explains the exception) make a copy first:
words = new ArrayList(words);
Upvotes: 0
Reputation: 3602
int i = 0;
for (Iterator<String> it = words.iterator(); it.hasNext(); )
{
it.next(); // Add this line in your code
if (i % 2 != 0)
{
it.remove();
}
i++;
}
Upvotes: 6
Reputation: 4202
You need to use next() and then call remove() ---
int counter = 0;
for (final Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
iterator.next();
if (++counter % 2 != 0) {
iterator.remove();
}
}
Upvotes: 0
Reputation: 948
The below also works fine
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 2, 3,
4, 5, 6, 7, 8, 9));
for (int i = 0; i < list.size(); i++) {
System.out.println(i);
list.remove(i);
}
System.out.println(list);
}
yielding
[2, 4, 6, 8]
Upvotes: 0
Reputation: 45070
Just use this.
for (int i = 1; i < list.size(); i++) {
list.remove(i);
}
Upvotes: 0
Reputation: 30855
You need to clone this Array or copy that odd element into another array. During iterate time it was used same object so if you remove its index and state was changes.
int i = 0;
List<String> list = new ArrayList<String>();
List<String> words = new ArrayList<String>();
for (String word:words)
{
if (i % 2 != 0)
{
//it.remove();
list.add(word);
}
i++;
}
words.removeAll(list);
now just remove this all by passing this list to your words list object
words.removeAll(list);
Upvotes: 2