我想不通,爲什麼我總是收到一個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[]
,但它不斷給我的錯誤
謝謝,你明白我在 –
@CupofJava請務必閱讀我答案的最後一句(「除非,當然」部分。) –
不是,謝謝你! –