2013-07-14 113 views
2

爲什麼我得到此代碼的錯誤?我有一個ArrayList中的正確進口的集合類型不匹配:無法從void轉換爲ArrayList <String>

private ArrayList<String> tips; 

public TipsTask(ArrayList<String> tips){ 
    this.tips = Collections.shuffle(tips); 
} 
+1

提示:* Collections.shuffle *的方法簽名是什麼?特別是,注意到錯誤信息(它說「不可能將void/nothing分配給ArrayList變量」),那麼shuffle會返回什麼? [documentation](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#shuffle(java.util.List))應該充分回答這個問題。對於類型錯誤,*總是*首先檢查相關定義/類型 - 沒有問題,只有不正確的用法。 – user2246674

回答

7
Collections.shuffle(tips); 

Collections.shuffle返回空隙,不能分配無效的ArrayList

例如,你可以這樣做:

    Collections.shuffle(tips); 
    this.tips = tips; 
3

的問題是,Collections.shuffle方法不返回任何東西。

你可以試試這個:

private ArrayList<String> tips; 

public TipsTask(ArrayList<String> tips){ 
    this.tips = new ArrayList<String>(tips); 
    Collections.shuffle(this.tips); 
} 
2

Collections.shuffle洗牌就地數組。這將是足夠的:

private ArrayList<String> tips; 

public TipsTask(ArrayList<String> tips){ 
    this.tips = tips; 
    Collections.shuffle(tips); 
} 

或者,如果你不想在最初的名單發生變化:

private ArrayList<String> tips; 

public TipsTask(ArrayList<String> tips){ 
    this.tips = new ArrayList<String>(tips); 
    Collections.shuffle(this.tips); 
} 
0

Collections.shuffle(tips)返回void。所以你不能指定這一個ArrayList()

你想要的是

private ArrayList<String> tips; 

public TipsTask(ArrayList<String> _tips){ 
    Collections.shuffle(_tips); 
    this.tips = _tips; 
} 
0

你應該稱呼它:

private ArrayList<String> tips; 

public TipsTask(ArrayList<String> tips){ 
    this.tips = tips; 
    Collections.shuffle(tips); 
} 

Collections.shuffle(TIPS)直接修改的ArrayList。它不需要創建副本。

0

我覺得你應該這樣寫:

private List<String> tips; 

public TipsTask(List<String> tips) { 
    this.tips = new ArrayList<String>(tips); 
    Collections.shuffle(this.tips); 
} 

另一種方式中斷上榜民營。具有原始參考的人可以操縱您的私人狀態。

相關問題