Collection Set constructor

1

I do not understand the difference between these two ways of declaring a constructor:

    Set<Integer> set1 = new HashSet<>();
    Set set2 = new HashSet();

For practical purposes there is a difference, because the two of them work or it seems that.

Thank you in advance, Best regards

    
asked by pelaitas 24.11.2018 в 16:52
source

1 answer

1

In the first statement you are using generics which will limit your structure (HashSet) to only support Integer type data in the second one by not using generics it supports any data of type Object and since practically everything in java would be an object including the primitive data through the wrapper class (Integer, Double etc) then you would have a structure that would support any type of data.

    public static void main(String[] args) {


    Set<Integer> set1 = new HashSet<>();
    Set set2 = new HashSet();


    set2.add(1);
    set2.add("string");
    set2.add(new Object());

    set1.add(1);
    set1.add("string"); //error de compilacion
    set1.add(new Object()); //error de compilacion
}
    
answered by 24.11.2018 в 17:25