Type mismatch: cannot convert from void to ArrayList

后端 未结 6 1311
别跟我提以往
别跟我提以往 2021-01-21 03:54

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

private ArrayList tips;

public TipsTask(ArrayLi         


        
相关标签:
6条回答
  • 2021-01-21 04:00

    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.

    0 讨论(0)
  • 2021-01-21 04:01

    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);
    }
    
    0 讨论(0)
  • 2021-01-21 04:01

    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;
    }
    
    0 讨论(0)
  • 2021-01-21 04:19
    Collections.shuffle(tips);
    

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

    you could do for example:

        Collections.shuffle(tips);
        this.tips = tips;
    
    0 讨论(0)
  • 2021-01-21 04:21

    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.

    0 讨论(0)
  • 2021-01-21 04:23

    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);
    }
    
    0 讨论(0)
提交回复
热议问题