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

Discussion

What will be the output of the program?

import java.util.*;

public class Sample35
{
    public static void main(String[] args)
    {
        List<Integer> l = new ArrayList<Integer>(
            Arrays.asList(1, 2, 3, 4));
        boolean changed = l.retainAll(Arrays.asList(2, 4, 6));
        System.out.println(changed + " " + l);
    }
}

  • A.The program prints true [1, 3]
  • B.false [1
  • C.The program prints true [2, 4]
  • D.The program prints true [2

Answer: C

retainAll keeps only the elements also present in the argument, so 1 and 3 go and 2 and 4 stay. The 6 is never added, because retainAll only ever removes. It returns true because the list changed, which is how the bulk operations report their effect.

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

Post your comment

Please log in or register to post a comment.