I faced below Interview question.
what is the output of the below code.
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 is giving output :10
But i am confuse why its output 10.
Anyone can answer me please what happening here.
Thanks
SItansu
The literal value 1
is of type int
. The value i - 1
is thus of type int
and not of type short
as i
is. You're thus adding boxed instances of Short
to the set, but removing boxed instances of Integer
. The remove()
method thus doesn't remove anything, because a Short
is not equal to an Integer
.
The expression i-1 has type int and is autoboxed to an Integer object, so the program is adding Short objects to the set and then tries to remove Integer objects. The set has no Integer objects, so nothing is ever removed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With