I'm doing a beginner Java tutorial on ArrayList that asks me to do the below
// Create a method called removeOdd
// Remove all the odd numbers from an ArrayList
// removeOdd(Arrays.asList(1,2,3,5,8,13,21)) => {2, 8}
// removeOdd(Arrays.asList(7,34,2,3,4,62,3)) => {34, 2, 4, 62}
The below is my code
import java.util.ArrayList;
import java.util.Arrays;
public class Ex4_RemoveOdd {
public static void main(String[] args) {
removeOdd((ArrayList<Integer>) Arrays.asList(1,2,3,5,8,13,21));
removeOdd((ArrayList<Integer>) Arrays.asList(7,34,2,3,4,62,3));
}
public static void removeOdd(ArrayList<Integer> list){
for (int i = 0; i < list.size(); i++){
int num = list.get(i);
if (num % 2 != 0){
list.remove(i);
}
}
System.out.println(list);
}
}
The code runs, but gives me the below error code
Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
Does anyone know what I did wrong?
I understand there is another similar question on SO
However I kind of think our situations are different since the OP did not declare a list within a method using AsList like I did.
Thanks so much for your time :)
System.out.println(list)does print meaningful output in my case. I get[2, 5, 8, 21]for my first run of theremoveOddmethodremoveOdd(Arrays.asList(1,2,3,5,8,13,21)), so as a beginner I got confused between what the api was saying and what the question was saying :/ That being said, I'll make sure to trust the API more than the question in the future