Cannot instantiate the type Set(无法实例化类型 Set)
问题描述
我正在尝试创建一组字符串,其中填充了来自 Hashtable 的键,因此 for-each 循环可以遍历 Set 并将默认值放入 Hashtable.我仍在学习 Java,但我尝试这样做的方式不是有效的语法.有人可以证明这样做的正确方法,并解释为什么我的方法行不通,而他们的方法行得通.
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));
}
}
}
推荐答案
Set
不是一个类,它是一个接口.
Set
is not a class, it is an interface.
所以基本上你只能实例化实现 Set
的类(HashSet
、LinkedHashSet
或TreeSet
)
So basically you can instantiate only class implementing Set
(HashSet
, LinkedHashSet
orTreeSet
)
例如:
Set<String> mySet = new HashSet<String>();
这篇关于无法实例化类型 Set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法实例化类型 Set
基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01