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

Discussion

What will be the output of the program?

import java.util.*;

public class Case68
{
    public static void main(String[] args)
    {
        Set<Integer> primes = new TreeSet<Integer>(
            Arrays.asList(2, 3, 5, 7));
        Set<Integer> odds = new TreeSet<Integer>(
            Arrays.asList(1, 3, 5, 7, 9));
        Set<Integer> both = new TreeSet<Integer>(primes);
        both.retainAll(odds);
        System.out.println(both + " " + primes.size());
    }
}

  • A.The program prints [2, 3, 5, 7] 4
  • B.[1, 2, 3, 5, 7, 9] 4
  • C.The program prints [3, 5, 7] 3
  • D.The program prints [3, 5, 7] 4

Answer: D

retainAll turns the receiver into the intersection, so the copy keeps the odd primes 3, 5 and 7 and drops 2. It modifies only the collection it is called on, so the original primes set is untouched at 4 elements. Copying first is what preserves it; calling retainAll on primes directly would have shrunk it.

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

Post your comment

Please log in or register to post a comment.