Discussion
What will be the output of the program?
import java.util.*;
public class Listing17
{
public static void main(String[] args)
{
Integer a = 1000, b = 1000;
Set<Integer> seen = new HashSet<Integer>();
seen.add(a);
seen.add(b);
System.out.println((a == b) + " " + seen.size());
}
}
Answer: A
1000 sits outside the guaranteed wrapper cache range of -128 to 127, so the two boxing conversions may create distinct objects and the identity test is false. The HashSet is unaffected by that: it uses equals and hashCode, which Integer implements by value, so the second add is a duplicate and the size is 1.
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