Return a new ArrayList with the even numbers from the nums array, in the same order.
evens(new int[] {3, 8, 10, 7}) returns [8, 10].
10 strips: Y1 to Y10
return result; Y1} Y2if (n % 2 == 0) { Y3ArrayList<Integer> result = new ArrayList<Integer>(); Y4} Y5public static ArrayList<Integer> evens(int[] nums) { Y6result.add(nums[n]); Y7} Y8for (int n : nums) { Y9result.add(n); Y10Order: Y6, Y4, Y9, Y3, Y10, Y5, Y2, Y1, Y8. Extra: Y7
public static ArrayList<Integer> evens(int[] nums) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int n : nums) {
if (n % 2 == 0) {
result.add(n);
}
}
return result;
} Extra strip: result.add(nums[n]);. In an enhanced for loop, n is the number itself, not an index. When n is 8, nums[8] is past the end of the array.