2013-12-19 58 views
-1

我無法理解爲什麼我的接口參數化不起作用。讓我們來看看下面的代碼:Java:原始類型對象內的泛型類型或爲什麼我的參數化不起作用

public interface IType { 
    public List<String> getAllItems(); 
} 

...... 
public void function(IType item) { 
    for (String str : item.getAllItems()) { //DOESN'T WORK! Incompoatible types. Required String, Found: Object 

    } 
} 

爲什麼它返回List<Object>代替List<String>

+1

泛型是編譯時。在運行時,它不像您想象的那樣運行。將其轉換爲'String'。 –

+0

是的,我可以施放列表引用。但實際上問題是爲什麼? –

+0

所以'列表 foo = item.getAllItems();'不起作用??? –

回答

6

我打算做一個假設,你的IType實際上是一個參數(你只不過是證實了它)型像這樣

public interface IType<E> { 
    public List<String> getAllItems(); 
} 

在這種情況下,如果聲明一個變量(或參數)爲

IType item; 

您正在使用原始類型。使用原始類型的變量時,在該變量上訪問的方法或字段中的所有泛型類型都將被刪除。所以

public List<String> getAllItems(); 

成爲

public List getAllItems(); 

等等ListIterator將返回Object類型的引用。

public void function(IType item) { 
    for (String str : item.getAllItems()) { // DOESN'T WORK! Incompoatible 
              // types. Required String, 
              // Found: Object 
    } 
} 

Combining Raw Types and Generic Methods

+0

謝謝,它是我想要的聽到。 –

+0

啊,神祕解決了。問題中不應該遺漏接口的泛型類型參數。魔鬼是在detai ;-) –

相關問題