2015-09-06 57 views
0

所以我有一些代碼,看起來像這樣:創建從通用的「對象」列表中的自定義對象的名單會越來越ClassCastException異常

public void success(List<Object> profiles, Response response) { 

    List<MyCustomObject> list= new ArrayList<MyCustomObject>(); 

    for (Object profile : profiles) { 
      list.add((MyCustomObject) profile); // this line crashes       
    } 

    } 

所以我得到了ClassCastException在橫線之上。我可以這樣做嗎?

這裏就是我要做的,我真正的代碼是一個比較複雜:

我有一個List包含兩種類型的對象。所以,我正在使用Object來支持這兩個。然後,一旦我從服務器收到這個列表,我想將列表分成兩個我的自定義對象列表(例如,List<MyCustomObject>而不是List<Object>。因此,我在for循環中執行上面的操作,以便我可以存儲傳入通用對象到其特定類型的對象名單。

是否有另一種方式做到這一點?我在正確的軌道上?

+1

使用「instanceof」運算符來確定哪個對象類型和路由到正確的列表。也許這個pu是否認爲設計的有效性? – OldProgrammer

+0

如果我正確地理解了你,那麼聲明兩個列表類型而不是轉換,如何使用一些條件,然後填充適當的列表? –

+0

@SandeepChatterjee這正是我想要做的,做的。但我的執行是有缺陷的。但看起來'instanceof'是我除了投射之外所需要的。 – KickingLettuce

回答

2

你應該投以防止代碼崩潰前添加一個安全檢查。

List<MyCustomObject> list= new ArrayList<MyCustomObject>(); 

    int index = 0; 
    for (Object profile : profiles) { 

     // Safety check before casting the object 
     if (profile instanceof MyCustomObject) { 
      list.add((MyCustomObject) profile); // wont crash now 
     } else { 
      // other type of object. Handle it separately 
     }     
    } 
+0

看起來像這個工作。謝謝。 – KickingLettuce

+3

儘管代碼解決了您的直接問題,但如果您正在傳遞'Objects'並使用'instanceof'對它們進行分箱,則看起來像有更大的設計問題。 'interface'和'abstract class'是你的朋友:) – Paul

+1

我同意@Paul。你應該考慮你的設計。 –

相關問題