Reputation: 305
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!
Upvotes: 2
Views: 474
Reputation: 32488
Since there are two overloaded remove()
methods in ArrayList
which one accepting int parameter as an index of the object and the other one accept Object
as parameter to remove.
You have use wrapper object to remove that element which is int. Otherwise, the overloaded remove(int index)
will be called and you don't have any element at index of 3, So, you got IndexOutOfBoundsException
while(al.contains(elem)){
al.remove(new Integer(elem));
}
Upvotes: 2
Reputation: 3694
You can do it simpler.
public int[] removeElement(int[] input, int deleteMe) {
List<Integer> result = new LinkedList();
for(int i=0;input.length;i++)
if(deleteMe!=input[i])
result.add(input[i]);
return result.toArray(input);
}
Upvotes: 5