Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot instantiate the type Set

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 still learning Java but the way I am trying to do it isn't valid syntax. Could someone please demonstrate the proper way of doing this and explain why my way doesn't work and theirs does.

private Hashtable<String, String> defaultConfig() {     Hashtable<String, String> tbl = new Hashtable<String, String>();     tbl.put("nginx-servers","/etc/nginx/servers");     tbl.put("fpm-servers","/etc/fpm/");     tbl.put("fpm-portavail","9001");     tbl.put("webalizer-script","/usr/local/bin/webalizer.sh");     tbl.put("sys-useradd","/sbin/useradd");     tbl.put("sys-nginx","/usr/sbin/nginx");     tbl.put("sys-fpmrc","/etc/rc.d/php_fpm");     tbl.put("www-sites","/var/www/sites/");     tbl.put("www-group","www");      return tbl; }  //This sets missing configuration options to their defaults. private void fixMissing(Hashtable<String, String> tbl) {     Hashtable<String, String> defaults = new Hashtable<String, String>(defaultConfig());     //The part in error is below...     Set<String> keys = new Set<String>(defaults.keySet());      for (String k : keys) {         if (!tbl.containsKey(k)) {             tbl.put(k, defaults.get(k));         }     } } 
like image 230
John Tate Avatar asked Sep 22 '13 17:09

John Tate


People also ask

Which type Cannot be instantiated?

Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class.

What does Cannot instantiate the type mean?

The InstantiationException is thrown when the JVM cannot instantiate a type at runtime. This can happen for a variety of reasons, including the following: The class object represents an abstract class, interface, array class, primitive or void . The class has no nullary constructor.

What implements set Java?

The Java platform contains three general-purpose Set implementations: HashSet , TreeSet , and LinkedHashSet .


1 Answers

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>(); 
like image 147
SegFault Avatar answered Oct 05 '22 21:10

SegFault