user5849987
user5849987

Reputation:

is there any difference between "Set<String> ss1 = new HashSet<>(m1.keySet());" and "Set<String> ss2 = m1.keySet();"

I'm learning Java Map interface and want to create an Set from Map 's key values. I have came up with two version of the code, they appears to be exactly the same to me. I was just wondering if there is any actually difference between them and when should I use one version over the other? Thanks in advance for any help.

    Map<String, Integer> m1 = new LinkedHashMap<>();
    m1.put("one", 1);
    m1.put("two", 2);
    m1.put("three", 3);

    //Version 1
    Set<String> ss1 = new HashSet<>(m1.keySet());

    //version 2
    Set<String> ss2 = m1.keySet();

Upvotes: 1

Views: 108

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198163

Yes, there is a difference. ss2 cannot have elements added to it, but if you remove elements from ss2 those keys will be correspondingly removed from the map.

ss1 has an independent existence from m1 and you can add and remove elements freely from it without affecting m1, though it also incurs O(n) overhead to do the copy.

Upvotes: 1

Related Questions