2014-09-04 118 views
0

我是Java的泛型特性的新手,我在其中一種方法中遇到了一些困難。 Eclipse給了我幾個警告,我想避免這些警告。該方法採用布爾標誌作爲其參數,並根據布爾值返回List<Integer>List<String>。我可以將該方法分解爲兩個,每個方法一個,但我寧願不把邏輯放在一個地方。避免Java泛型警告?

簡化方法與警告的評論:

private <T> List<T> getList(boolean returnInt) { 
    // List is a raw type. References to generic type List<E> should be parameterized 
    List returnList; 
    if (returnInt) { 
     returnList = new ArrayList<Integer>(); 
    } else { 
     returnList = new ArrayList<String>(); 
    } 

    if (mShowNew) { 
     if (returnInt) { 
      // Type safety: The method add(Object) belongs to the raw type List. 
      // Refs to generic type List<E> should be parameterized. 
      returnList.add(ID_NEW); 
     } else { 
      // Type safety: The method add(Object) belongs to the raw type List. 
      // Refs to generic type List<E> should be parameterized. 
      returnList.add("New"); 
     } 
    } 
    if (mResume) { 
     if (returnInt) { 
      returnList.add(ID_RESUME); 
     } else { 
      returnList.add("Resume"); 
     } 
    } 
    // Pattern continues 

    // Type safety: The expression of type List needs unchecked conversion to 
    // conform to List<T> 
    return resultList; 
} 

我能更改,以避免這些警告?如果完全有更好的方法,我們將不勝感激正確的方向。

+1

爲什麼不只是讓兩個單獨的函數,它返回一個int,另一個是字符串? – Pokechu22 2014-09-04 01:19:01

+1

這樣返回兩種列表是一個非常糟糕的主意。無論如何,你的原始類型可能是'List returnList;'(但是,這又是一個壞主意)。 – 2014-09-04 01:20:25

+1

@ElliottFrisch表示Java不是一種動態語言,你不應該混淆類型系統和泛型(不管你認爲它們有多糟糕:-)) – 2014-09-04 01:32:52

回答

1

創建一個同時擁有一個IntegerString

例如一個新的類

public class Result { 
    private String stringResult = null; 
    private Integer intResult = null; 
    } 

填寫此要求,並以此作爲

List<Result> returnList; 

當然也有你的方法返回此

private List<Result> getList(boolean returnInt) { 
0

如果參數只是用來確定嵌套式resturnd列表,那麼你可以除了類型作爲參數來指定所需的列表類型。

這可能是這樣的:

private <T> List<T> getList(Class<T> listType) { 
    if (!(listType.getClass().equals(Integer.class) 
      || listType.getClass().equals(String.class))) { 
     throw new IllegalArgumentException(
      String.format("Type '%s' is currently not supported.", listType.getClass().getName())); 
    } 

    // v--- the missing type specification was causing the warnings you mentioned 
    List<T> returnList = new ArrayList<>(); 

    if (mShowNew) { 
     if (listType.getClass().equals(Integer.class)) { 
      returnList.add(ID_NEW); 
     } else { 
      returnList.add("New"); 
     } 
    } 

    if (mResume) { 
     if (listType.getClass().equals(Integer.class)) { 
      returnList.add(ID_RESUME); 
     } else { 
      returnList.add("Resume"); 
     } 
    } 

    //... 
    return resultList; 
}