2016-09-25 24 views
0

我想不通,爲什麼我總是收到一個java.lang.ClassCastException: java.lang.Object; cannot be cast to ProfileInterface錯誤無法施展對象的陣列到另一個界面的陣列

這裏是所有不斷給我的錯誤

客戶

public static void show() { 
    ProfileInterface person = pick(); 
    if (person == null){ 
     return; 
    } 
    System.out.println(p.getName()); 
    System.out.println("About: " + p.getAbout()); 
    System.out.println("Following:"); 

    //error happens at this line below 
    ProfileInterface[] following = p.following(4); 

    for (ProfileInterface p2 : following) { 
     System.out.println(p2.getName()); 
    } 
} 
相關代碼包含 following方法和延伸ProfileInterface

private Set<ProfileInterface> friends = new Set<ProfileInterface>(); 

public ProfileInterface[] following(int count){ 
    if(count >= friends.getCurrentSize()){ 

     //And points to this line as the Object Cast Error 
     return (ProfileInterface[])friends.toArray(); 

    }else{ 
     return (ProfileInterface[])Arrays.copyOf(friends.toArray(), howMany); 
    } 
} 

Profile類

和一組類,包含toArray方法

@Override 
public T[] toArray() { 
    T[] returnArray = (T[])new Object[size]; 
    System.out.println("Size of current array is " +size); 
    for(int i = 0; i < size;i++){ 
     returnArray[i] = setArray[i]; 
    } 

    return returnArray; 
} 

我鑄造返回的數組爲ProfileInterface[],但它不斷給我的錯誤

回答

1

在我看來,你有以下幾種選擇:

  1. 離開的Set實施,因爲它是實現您following()方法,而不必調用toArray(),希望沒人會調用toArray(),因爲如果他們這樣做,它會炸燬。

  2. 轉到誰給你的任務,並抗議說,分配給出的指導方針不能得到合理的解決方案,因爲誰設計了Set接口顯然從來沒有實現過,或從未嘗試調用它們的實施toArray()方法。如果他們這樣做了,他們會遇到同樣的錯誤。

  3. 修改類實現Set的構造函數接受類的元素,(所以理論上講,你將不會被改變的Set接口,),因此它會通過如下方式調用:

Set<ProfileInterface> following = new Set<>(ProfileInterface.class);

然後,使用下面的方法從toArray()內建立一個數組:

public static <T> T newArray(Class<T> arrayType, int size) 
{ 
    assert arrayType.isArray(); 
    @SuppressWarnings("unchecked") 
    T array = (T)Array.newInstance(arrayType.getComponentType(), size); 
    return array; 
} 

(你可能想用它玩了一下,以滿足您的需求,例如,你可能希望它返回T[]而不是T。)

除非,當然,Set界面你試圖實施的是java.util.Set,在這種情況下,它已經有一個toArray(T[])方法,您可以覆蓋而不是T[] toArray()

+1

謝謝,你明白我在 –

+0

@CupofJava請務必閱讀我答案的最後一句(「除非,當然」部分。) –

+0

不是,謝謝你! –

相關問題