Problem: Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length.
I want to solve this question by using JAVA ArrayList. And by code is listed as follows:
import java.util.ArrayList;
import java.util.Arrays;
public class removeElement {
/**
* @param args
*/
public int removeElement(int[] A, int elem) {
int length = 0;
ArrayList<Integer> al = new ArrayList<Integer>();
Arrays.sort(A);
//add elements in A to al
for(int i:A){
al.add(i);
}
//Remember arraylist's remove() is to remove first occurance of elements.
if(al.contains(elem)&&al.size() == 1){
return 0;
}
while(al.contains(elem)){
al.remove(elem);
}
length = al.size();
return length;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
removeElement re = new removeElement();
int[] A = {3, 3};
int element = 3;
System.out.println(re.removeElement(A, element));
}
}
The result shows that:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:571)
at java.util.ArrayList.remove(ArrayList.java:412)
at removeElement.removeElement(removeElement.java:24)
at removeElement.main(removeElement.java:35)
Can I use JAVA ArrayList to solve this problem? Or should I solve it in another way? Waiting for your reply. Thanks a lot!