2012-01-27 44 views
3

有,說:「不安全的操作」,所以我用-Xlint警告:未選中看到這些操作,但我不明白我在做什麼錯。這些是警告,然後我的代碼謝謝!-Xlint:清洗&建立我的項目在NetBeans未選中時在NetBeans

UploadBean.java:40: warning: [unchecked] unchecked conversion 
    private final List fileList = Collections.synchronizedList(new ArrayList()); 
    required: List<T> 
    found: ArrayList 
    where T is a type-variable: 
    T extends Object declared in method <T>synchronizedList(List<T>) 


UploadBean.java:40: warning: [unchecked] unchecked method invocation: method synchronizedList in class Collections is applied to given types 
    private final List fileList = Collections.synchronizedList(new ArrayList()); 
    required: List<T> 
    found: ArrayList 
    where T is a type-variable: 
    T extends Object declared in method <T>synchronizedList(List<T>) 


UploadBean.java:97: warning: [unchecked] unchecked call to add(E) as a member of the raw type List 
        fileList.add(fd); 
    where E is a type-variable: 
    E extends Object declared in interface List 
3 warnings 

CODE

//This is line 40  
private final List fileList = Collections.synchronizedList(new ArrayList()); 

//This is line 88 
public void doUpload(FileEntryEvent e) { 
     FileEntry file = (FileEntry) e.getSource(); 
     FileEntryResults result = file.getResults(); 
     for (FileInfo fileInfo : result.getFiles()) { 
      if (fileInfo.isSaved()) { 
       FileDescription fd = 
         new FileDescription(
         (FileInfo) fileInfo.clone(), getIdCounter()); 
       synchronized (fileList) { 
        fileList.add(fd); //This is line 97 
       } 
      } 
     } 
    } 

歡呼

回答

6

您需要了解Java的泛型。舊的1.4風格仍然可以編譯,但它會通過警告(認爲某些錯誤)。

由於您使用的期望泛型類型參數的類,他們需要被指定爲編譯器,像這樣:

//This is line 40  
private final List<FileDescription> fileList = Collections.synchronizedList(new ArrayList<FileDescription>()); 

//This is line 88 
public void doUpload(FileEntryEvent e) { 
     FileEntry file = (FileEntry) e.getSource(); 
     FileEntryResults result = file.getResults(); 
     for (FileInfo fileInfo : result.getFiles()) { 
      if (fileInfo.isSaved()) { 
       FileDescription fd = 
         new FileDescription(
         (FileInfo) fileInfo.clone(), getIdCounter()); 
       synchronized (fileList) { 
        fileList.add(fd); //This is line 97 
       } 
      } 
     } 
    } 

注意泛型,某些類型的鑄件不再是必要的。例如,fileList.get(0)將在上面的示例中返回FileDescription,而不需要執行顯式強制轉換。

該泛型參數指示無論存儲在fileList內必須是「至少」一個FileDescription。編譯器檢查是否不可能將非FileDescription項放入列表中,並且輸出代碼實際上不會執行任何運行時檢查。因此,泛型實際上不會像其他語言中的類似技術那樣遭受性能命中,但是編譯器執行的「類型擦除」會使某些技術無法像通用參數的運行時類型分析一樣。

試一試,你會喜歡它們的。

如果此代碼是在Generics發佈之前編寫的,則可能需要使用向後兼容標誌(-source 1.4 -target 1.4)進行編譯。

1

您的列表中使用類型,如:

List<Object> l = new ArrayList<Object>(); 

或用JDK7和鑽石操作符,你可以使用:

List<Object> l = new ArrayList<>(); 

所以在代碼中使用:

private final List <FileDescription> fileList = Collections.synchronizedList(new ArrayList<FileDescription>());