2013-04-14 62 views
0

queryMe方法返回一個ArrayIterator < Me>。 queryYou方法返回一個ArrayIterator < You>。Java Casting ArrayIterator <Object>

public ArrayIterator<Object> query(String table, String field, String criterion) 
{ 
    ArrayIterator<Object> result = null; 

    if (table.equals("MyTable") 
    { 
     result = MyTable.queryMe(field, criterion); 
    } 
    else if (table.equals("YourTable") 
    { 
     result = YourTable.queryYou(field, criterion); 
    } 

    return result; 
} 

我收到說

ArrayIterator<Me> and ArrayIterator<Java.lang.object> are incompatible types. 

任何建議的錯誤?

+0

由於錯誤說,我覺​​得你應該創建和類型,而不是與類型的對象 – cakil

+0

返回ArrayIterator返回ArrayIterator這種方法比複雜得多,它具有許多其他if語句。爲了簡單起見,我只發佈了一個。我即將編輯它。 –

+0

認爲ArrayIterator 是ArrayIterator 的子類是泛型的常見誤解,因爲Me是Object的子類。但它不會那樣工作。有關泛型的任何教程都可以解釋原因。 – arcy

回答

0

這裏是黑客你在追求。首先將其轉換爲原始ArrayIterator,然後轉換爲ArrayIterator <Me>。

ArrayIterator <Me> meIter =(ArrayIterator)結果。

更好的方法是將您的方法更改爲返回ArrayIterator <Me>並將結果更改爲相同。

***剛剛看到您的更新。看來該方法試圖返回不同類型的ArrayIterator,因此返回類型爲<Object>。

// Would be nice if the 2 types shared a common super type. 
public ArrayIterator<Object> query(String table, String field, String criterion) 
{ 
    // WARNING, this is a raw generic type, and provides no type safety 
    ArrayIterator result = null; 

    if (table.equals("MyTable") 
    { 
     result = MyTable.queryMe(field, criterion); 
    } 
    else if (table.equals("YourTable") 
    { 
     result = YourTable.queryYou(field, criterion); 
    } 
    return (ArrayIterator<Object>) result. 
} 
+0

謝謝你,那正是我正在尋找的。 –

2

你不能投,因爲ArrayIterator<Me>不是其實ArrayIterator<Java.lang.object>亞型,這兩種類型都沒有關係。

Find more explanation

+0

任何原因-ve ??? :( –

0

你不能轉換ArrayIterator<Me>ArrayIterator<Object>,你應該改變queryMe功能 的返回類型,但如果你是迭代器總是有類型Me它得到更好的整體使用ArrayIterator<Me>程序