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

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());
    }
}

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

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.