2011-10-24 54 views
2

所以,我得到的是:ArrayList.toArray()不轉換爲正確的類型?

class BlahBlah 
{ 
    public BlahBlah() 
    { 
     things = new ArrayList<Thing>(); 
    } 

    public Thing[] getThings() 
    { 
     return (Thing[]) things.toArray(); 
    } 

    private ArrayList<Thing> things; 
} 

在其他類我:

for (Thing thing : someInstanceOfBlahBlah.getThings()) 
{ 
    // some irrelevant code 
} 

和錯誤是:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LsomePackage.Thing; 
at somePackage.Blahblah.getThings(Blahblah.java:10) 

我怎樣才能解決這個問題?

+0

我不認爲你可以。或者說,我不認爲你可以轉換Array對象,因爲它是一個Object []'。但我相信你可以投出每個單獨的陣列 - 元素 - 。 – BenCole

回答

8

嘗試:

public Thing[] getThings() 
{ 
    return things.toArray(new Thing[things.size()]); 
} 

的原因,你的原始版本不工作是toArray()回報Object[]而不是Thing[]。您需要使用其他形式的toArray - toArray(T[]) - 才能獲得Things的數組。

+1

'.size()'而不是'.length'。否則+1 – Bozho

+0

@Bozho:已經修復,謝謝。 – NPE

+0

參數不需要有「正確」的大小,它只是需要類型信息iirc。所以你可以使用'new Thing [0]'作爲參數,或者更好的方法是用一個靜態的最終常量來使用Peter Lawrey的方法。 – MartinStettner

4

嘗試

private static final Thing[] NO_THING = {}; 

return (Thing[]) things.toArray(NO_THING); 
0

2 toArray() functions

Object[] toArray() 
     Returns an array containing all of the elements in this list in the correct order. 
    <T> T[] toArray(T[] a) 
     Returns an array containing all of the elements in this list in the correct order; 
     the runtime type of the returned array is that of the specified array. 

您使用的是第一位的,這是應該返回Object[]和它這樣做。如果你想獲得正確的類型使用第二個版本:

things.toArray(new Thing[things.length]); 

,或者如果你不想浪費任何new Thing[things.length]更多的空間,那麼就改變回路投:

Thing thing = null; 
for (Object o : someInstanceOfBlahBlah.getThings()) 
{ 
    thing = (Thing) o; 
    // some unrelevant code 
} 
相關問題