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); } 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); } Collections.shuffle(tips); Collections.shuffle return void, you cannot assign void to a ArrayList.
you could do for example:
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); } 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); } 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; } 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.
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.