Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

import java.util.*;

public class Probe02
{
    public static void main(String[] args)
    {
        List<Integer> codes = new ArrayList<Integer>(
            Arrays.asList(5, 7, 9, 5));
        codes.remove(Integer.valueOf(5));
        System.out.println(codes.size() + " " + codes);
    }
}

  • A.An IndexOutOfBoundsException is thrown.
  • B.The program prints 3 [7, 9, 5]
  • C.The program prints 4 [5, 7, 9, 5]
  • D.The program prints 2 [7, 9]

Answer: B

Wrapping the argument forces the remove(Object) overload, so the list is searched for the VALUE 5 and only the FIRST match is removed, leaving [7, 9, 5] with a size of 3. remove(Object) stops after one element; removeAll would have taken both. Written as remove(5) it would have been read as an index instead.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.