今天在使用MAP時,用了泛型,但是編譯時報了一個錯,開始感到很納悶,源代碼如下:
import java.util.*;

public class TestMap2{
private static final Integer ONE = new Integer(1);
public static void main(String[] args){
Map<String> m = new HashMap<String>();
for(int i = 0; i < args.length; i++){
Integer freq = m.get(args[i]);
m.put(args[i],(freq == null ? ONE : new Integer(freq.intValue() + 1)));
}
System.out.println(m.size() + "distinct words detected!");
System.out.println(m);
}
}
編譯時報錯為:類型變量數目錯誤,需要2
開始感到很奇怪,查了API才發現MAP的泛型用法錯誤,正確的用法應該是下面這樣的:
import java.util.*;

public class TestMap2{
private static final Integer ONE = new Integer(1);
public static void main(String[] args){
Map<String,Integer> m = new HashMap<String,Integer>();
for(int i = 0; i < args.length; i++){
Integer freq = m.get(args[i]);
m.put(args[i],(freq == null ? ONE : new Integer(freq.intValue() + 1)));
}
System.out.println(m.size() + "distinct words detected!");
System.out.println(m);
}
}
這時,編譯就沒問題了!
QQ交流群:90623790
















開始感到很奇怪,查了API才發現MAP的泛型用法錯誤,正確的用法應該是下面這樣的:
















這時,編譯就沒問題了!
QQ交流群:90623790