无法实例化类型 Set

Cannot instantiate the type Set(无法实例化类型 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 的类(HashSetLinkedHashSetTreeSet)

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

例如:

Set<String> mySet = new HashSet<String>();

这篇关于无法实例化类型 Set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:无法实例化类型 Set

基础教程推荐