Cannot instantiate the type Set

前端 未结 3 2045
春和景丽
春和景丽 2021-01-03 18:51

I am trying to create a Set of Strings which is filled with the keys from a Hashtable so a for-each loop can iterate through the Set and put defaults in a Hashtable. I am st

相关标签:
3条回答
  • 2021-01-03 19:03

    Set is an interface. You cannot instantiate an interface, only classes which implement that interface.

    The interface specifies behaviour, and that behaviour can be implemented in different ways by different types. If you think about it like that, it makes no sense to instantiate an interface because it's specifying what a thing must do, not how it does it.

    0 讨论(0)
  • 2021-01-03 19:06

    Set is not a class, it is an interface.

    So basically you can instantiate only class implementing Set (HashSet, LinkedHashSet orTreeSet)

    For instance :

    Set<String> mySet = new HashSet<String>();
    
    0 讨论(0)
  • 2021-01-03 19:12

    HashMap's keySet() method already creates the set you need, so simply:

    Set<String> keys = defaults.keySet();
    

    This is a view of the keys in defaults, so its contents will change when changes are made to the underlying (defaults) map. Changes made to keys will be reflected in the map, as well, but you can only remove...not add...keys from the map.

    If you need a copy of the keys that doesn't interact with the original map, then use one of the types suggested, as in:

    Set<String> keys = new HashSet( defaults.keySet() );
    
    0 讨论(0)
提交回复
热议问题