2015-11-10 46 views
4
class User{ 
    private int id; 
    private String name; 

    public User(int id, String name) { 
     this.id = id; 
     this.name = name; 
    } 
} 

class Service<T> { 
    private List<T> data; 
    public void setData(List<T> data) { 
     this.data = data; 
    } 
} 

public class ServiceTest { 
    public static void main(String[] args) { 
     Service<User> result=new Service<User>(); 
     result.setData(Collections.emptyList()); // problem is here 
    } 
} 

如何通過類型參數傳遞空列表?如何通過類型參數傳遞空列表?

編譯器給我的錯誤信息:

The method setData(List< User >) in the type Service is not applicable for the arguments (List< Object >)

,如果我試圖用列表來投那麼錯誤:

Cannot cast from List< Object > to List< User >

result.setData(new ArrayList<User>());工作正常,但我不想把它傳遞。

+0

它適用於Java的8 – ZhongYu

回答

9

Collections.emptyList()是通用的,但你在它的原始版本使用。

您可以明確設置類型參數有:

result.setData(Collections.<User>emptyList()); 
6

簡單 result.setData(Collections.<User>emptyList());

0

The issue you're encountering is that even though the method emptyList() returns List, you haven't provided it with the type, so it defaults to returning List. You can supply the type parameter, and have your code behave as expected, like this:

result.setData(Collections.<User>emptyList()); 

Now when you're doing straight assignment, the compiler can figure out the generic type parameters for you. It's called type inference. For example, if you did this:

List<User> emptyList = Collections.emptyList(); 

then the emptyList() call would correctly return a List.