大家好,我对此代码有疑问:
//Class FileManip
public class FileManip{
private HTTPRequest<List<String>> addMe = new HTTPRequest<List<String>>();
public void openFile(){
try{
BufferedReader buff = new BufferedReader(new FileReader("Saturday.txt"));
try{
Double ctr = 0.0;
String readHTTPURIFromTxt = buff.readLine();
while (readHTTPURIFromTxt!=null){
if (!readHTTPURIFromTxt.isEmpty()){
addMe.putListHTTPCharTable(parseHTTPReqToCharbyChar(readHTTPURIFromTxt), ctr);
ctr++;
}
readHTTPURIFromTxt = buff.readLine();
}
}
finally{
buff.close();
}
}
catch(FileNotFoundException e){
System.out.println("File not found"+e);
}
catch(IOException e){
System.out.println("oist exception");
}
}
public List<String> parseHTTPReqToCharbyChar(String getHTTP){
List<String> parsingReq = new ArrayList<String>();
String convChar=null;
for (int x = 0; x<getHTTP.length(); x++){
convChar = Character.toString(getHTTP.charAt(x));
parsingReq.add(convChar);
}
return parsingReq;
}
}
//Class HTTPRequest
public class HTTPRequest<T> {
private LinkedHashMap<List<T>, Double> tableOfInitProbList = new LinkedHashMap<List<T>, Double>();
public HTTPRequest(){
}
public HTTPRequest(List<T> entry, Double value){
tableOfInitProbList.put(entry, value);
}
public void putListHTTPCharTable(List<T> uri, Double value){
tableOfInitProbList.put(uri, value);
}
}
问题在于
行addMe.putListHTTPCharTable(parseHTTPReqToCharbyChar(readHTTPURIFromTxt), ctr);
在if语句中的类filemanip openfile方法。我写了putListHttpCharTable来取2个参数List&lt; T>和Double但每当我传递参数parseHTTPReqToCharbyChar(readHTTPURIFromTxt)时返回类型为List,就会出现编译时错误。它读取
方法putListHTTPCharTable(List&gt;,Double)类型为HTTPRequest&gt;不适用于参数(List,Double)
我传递了一个List&lt;字符串&gt;返回类型,但不知何故编译器正试图将其读作List&lt;列表&lt; T> &GT;或列表&lt;列表&lt;字符串&gt; &GT;而不仅仅是List&lt;字符串&gt;。无论如何要解决这个问题吗?
答案 0 :(得分:3)
因为:
HTTPRequest<List<String>>
表示:
T <=> List<String>
所以编译器会看到这个(对于你的&#34; addMe&#34;变量):
//Class HTTPRequest
public class HTTPRequest<List<String>> {
private LinkedHashMap<List<List<String>>, Double> tableOfInitProbList = new LinkedHashMap<List<List<String>>, Double>();
public HTTPRequest(){
}
public HTTPRequest(List<List<String>> entry, Double value){
tableOfInitProbList.put(entry, value);
}
public void putListHTTPCharTable(List<List<String>> uri, Double value){
tableOfInitProbList.put(uri, value);
}
}
答案 1 :(得分:2)
您将T
设为List<String>
然后该方法正在寻找List<T>
,因此您最终得到List<List<String>>
如果您将班级更改为:
,这应该有效public class HTTPRequest<T> {
private LinkedHashMap<T, Double> tableOfInitProbList = new LinkedHashMap<List<T>, Double>();
public HTTPRequest(){
}
public HTTPRequest(T entry, Double value){
tableOfInitProbList.put(entry, value);
}
public void putListHTTPCharTable(T uri, Double value){
tableOfInitProbList.put(uri, value);
}
}
或者,如果您只想使用泛型参数指定列表类型,则此声明应该起作用:
private HTTPRequest<String> addMe = new HTTPRequest<String>();