Set java puzzle

I came across an interview question.

what is the result of the code below.

package com.demo; import java.util.HashSet; import java.util.Set; public class Test { public static void main(String[] args) { Set<Short> set=new HashSet<Short>(); for (short i = 0; i < 10; i++){ set.add(i); set.remove(i-1); } System.out.println(set.size()); } } 

It displays the result: 10

But I'm confused why its output is 10.

Anyone can answer me, please, what is happening here.

thanks

SItansu

+5
source share
2 answers

The literal value 1 is of type int . Thus, the value of i - 1 is of type int , and not of type short as i . Thus, you add nested short instances to the set, but delete instances in the Integer box. Thus, the remove() method does not remove anything, since short not equal to Integer .

+5
source

The expression i-1 is of type int and is auto-boxed to the Integer object, so the program adds short objects to the set and then tries to delete the Integer objects. The collection has no Integer objects, so nothing is deleted.

+5
source

Source: https://habr.com/ru/post/1234844/


All Articles