Jake Schleben February 2016

Deleting a specific number in an ArrayList

I am running into a problem in my code. I have an Arraylist, and I have a bunch of zeros that I need to remove. They are mixed in with other numbers, which I want to keep. However, when I do a for loop, it will skip over some zeros and won't remove them. Here my code:

public static void main(String[] args) throws FileNotFoundException
{
     Scanner scan = new Scanner(new File("input.txt"));
     ArrayList<Double> list = new ArrayList<Double>();
     while(scan.hasNextLine()){
         list.add(scan.nextDouble());
     }

     for(int i=1; i<list.size();i+=4){
         if(list.get(i)<150000){
             list.set(i-1,(double) 0);
             list.set(i,(double) 0);
             list.set(i+1,(double) 0);
             list.set(i+2,(double) 0);
         }
     }

     for(int i=2; i<list.size();i+=4){
         if(list.get(i)>22.2){
             list.set(i-2,(double) 0);
             list.set(i-1,(double) 0);
             list.set(i,(double) 0);
             list.set(i+1,(double) 0);
         }
     }

     for(int i=3; i<list.size();i+=4){
         if(list.get(i)<1100){
             list.set(i-3,(double) 0);
             list.set(i-2,(double) 0);
             list.set(i-1,(double) 0);
             list.set(i,(double) 0);
         }
     }

     for(int i=0;i<list.size();i++){
         if(list.get(i)==0){
             list.remove(i);
         }
     }

     System.out.println(list);
 }
}

Any help would be greatly appreciated!

Answers


Pablo Rivero February 2016

You are structurally modifying the list while you remove the 0's. Use an iterator

while (iterator.hasNext()) {
   int elem = iterator.next(); 
   if (elem == 0)
     iterator.remove();
} 

Hope it helps. PD: You can include code directly in the question text using the "{}" button


Ken Bekov February 2016

This is you problem:

for(int i=0;i<list.size();i++)
{
   if(list.get(i)==0)
   {
      list.remove(i);
   }
}

Look, let's say, you found 0 value at i=2. You removing item with index 2. All list items, that was after 2 item will shift up. So, 3 item will become 2, 4 will become 3 and so on. But you incrementing i and skiping next (shifted up) item.

You have keep index if you found 0 value and increment it else:

int i=0;
while(i<i<list.size()){
    if(list.get(i)==0){
       list.remove(i);
    }else{
       i++;
    }
}

Post Status

Asked in February 2016
Viewed 1,103 times
Voted 4
Answered 2 times

Search




Leave an answer