Type mismatch: cannot convert from void to ArrayList<String>

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

Why am I getting this error for this code? I have the correct imports for ArrayList an Collections

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

回答1:

Collections.shuffle(tips); 

Collections.shuffle return void, you cannot assign void to a ArrayList.

you could do for example:



回答2:

The problem is that Collections.shuffle method doesn't return anything.

You can try this:

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


回答3:

Collections.shuffle shuffles the array in-place. This will be sufficient:

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

Or if you don't want the original list to change:

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


回答4:

Collections.shuffle(tips) returns void. So you cannot assign this to an ArrayList()

What you want is

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


回答5:

You should call it like this:

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

Collections.shuffle(tips) modifies the ArrayList directly. It does not need to create a copy.



回答6:

I think you should write it like this:

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

The other way breaks making the List private. The person with the original reference can manipulate your private state.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!