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());
}
}
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.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development