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

Discussion

What will be the output of the program?

import java.util.*;

public class Snippet04
{
    public static void main(String[] args)
    {
        Set<String> s = new HashSet<String>();
        System.out.println(s.add("x") + " " + s.add("x") + " " + s.size());
    }
}

  • A.The program prints false true 1
  • B.The program prints true true 1
  • C.The program prints true true 2
  • D.The program prints true false 1

Answer: D

Correct answer: The program prints true false 1

Set.add returns whether the set was changed by the call. The first add inserts the element and returns true; the second finds it already present, changes nothing and returns false. The size is therefore 1. That boolean return is worth knowing in its own right - it is the idiomatic way to test and insert in one operation.

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

Post your comment

Please log in or register to post a comment.