LearnFrenzy
Sign in Take a free test

Object Class and Wrapper Classes · Predict the Output · Question 2

Removing from a Set of Short values Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<Short> set = new HashSet<>();
        for (short i = 0; i < 10; i++) {
            set.add(i);
            set.remove(i - 1);            // i - 1 is an int, boxed to Integer
        }
        System.out.println(set.size());
    }
}
  • A 10 Correct
  • B 1
  • C 0
  • D 9
Correct Answer: Option A

remove(Object) receives an Integer, which never equals a Short, so nothing is removed.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links