Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java interview puzzle related to set [duplicate]

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

like image 521
Sitansu Avatar asked Oct 30 '15 06:10

Sitansu


2 Answers

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.

like image 186
JB Nizet Avatar answered Oct 09 '22 14:10

JB Nizet


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.

like image 32
Joni Avatar answered Oct 09 '22 14:10

Joni