I wrote this program to find the item and then to remove all elements which are smaller than the item. The are no compilation errors, but when I run the program, the following message appears.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.remove(ArrayList.java:492)
at bb.deleteValues(bb.java:15)
at bb.main(bb.java:33)
Process completed. "
Code:
import java.util.ArrayList;
import java.util.Scanner;
public class bb {
public static boolean deleteValues(ArrayList<Integer> list, int item)
{ int p =list.indexOf(item);
if(!list.contains(item))
return false;
else
for(int i=p; i<list.size();i++ )
{int n=list.get(i);
if (n>list.get(i+1))
list.remove(p);
list.remove(i+1);
}
return true;
}
public static void main(String[] args) {
ArrayList<Integer> a= new ArrayList<Integer>(8);
a.add(3);
a.add(10);
a.add(4);
a.add(5);
a.add(3);
a.add(2);
a.add(8);
a.add(6);
a.add(4);
if(deleteValues(a,4))
for(int x : a)
System.out.print(x+ " ");
}
}