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

Discussion

What will be the output of the program?

import java.util.*;

public class Trial31
{
    public static void main(String[] args)
    {
        Set<String> tags = new TreeSet<String>();
        tags.add("beta");
        tags.add("alpha");
        System.out.print(tags.first() + " ");
        tags.add(null);
        System.out.println(tags);
    }
}

  • A.alpha [alpha, beta]
  • B.alpha [null, alpha, beta]
  • C.alpha, then a NullPointerException
  • D.beta, then a NullPointerException

Answer: C

first returns the lowest element under the natural ordering, which is alpha, and that prints. Adding null then fails: a TreeSet must compare each new element against those present, and comparing null throws NullPointerException. A HashSet accepts a single null happily, needing only a hash and equality.

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

Post your comment

Please log in or register to post a comment.