我正在使用此方法从属性文件中读取:
#include <iostream>
#include<string>
using namespace std;
int main (){
string star = "*";
int a=2;
while(a<=6){
cout<<a<<star*(a/2)<<endl;
a+=2;
}
return 0;
}
要写入的字段声明如下:
public void loadConfigFromFile(String path) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(path);
prop.load(input);
/*saved like this:*/ //emails: abc@test.com, bbc@aab.com, ..
String wordsS = prop.getProperty("keywords");
String emailS = prop.getProperty("emails");
String feedS = prop.getProperty("feeds");
emails = Arrays.asList(emailS.split(",")); //ERROR !!
words = Arrays.asList( wordsS.split(","))); //ERROR !!
feeds = Arrays.asList( feedS.split(",")); //ERROR !!
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
..所以编译器向我展示了以下信息,我不知道如何使用:
不兼容的类型。必需
private ArrayList<String> emails = new ArrayList<>( Arrays.asList("f00@b4r.com", "test@test.com") ); private LinkedList<String> words = new LinkedList<>( Arrays.asList("vuln", "banana", "pizza", "bonanza") ); private LinkedList<String> feeds = new LinkedList<>( Arrays.asList("http://www.kb.cert.org/vulfeed", "https://ics-cert.us-cert.gov/advisories/advisories.xml") );
,但'asList'被推断为ArrayList<String>
:没有类型变量T的实例存在,以便List<T>
符合List<T>
如何规避这个?
答案 0 :(得分:4)
问题是您指定的声明变量的类型
emails = Arrays.asList(emailS.split(","));
。
根据编译错误,它被声明为ArrayList
,但Arrays.asList()
返回List
。
在您可以执行相反操作时,您无法将List
分配给ArrayList
。
除了Arrays.asList()
之外,还会返回私有类的实例:java.util.Arrays.ArrayList
,它与您声明的ArrayList
变量不同:java.util.ArrayList
。因此,即使向ArrayList
投降,也无效,导致ClassCastException
。
更改声明的变量
ArrayList<String> emails
到List<String> emails
并为另外两个ArrayList
变量做同样的事情。