【问题标题】:Type mismatch: cannot convert from void to ArrayList<String>类型不匹配:无法从 void 转换为 ArrayList<String>
【发布时间】:2013-07-15 06:35:59
【问题描述】:

为什么我收到此代码的此错误?我对 ArrayList 和 Collections 有正确的导入

private ArrayList<String> tips;

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

【问题讨论】:

  • 提示:Collections.shuffle 的方法签名是什么?特别是,注意错误消息(它说“不可能将 void/nothing 分配给 ArrayList 变量”),shuffle 返回什么? documentation 应该足以回答这个问题。对于类型错误,总是首先检查相关的定义/类型 - 没有问题,只有不正确的用法。

标签: java arraylist


【解决方案1】:
Collections.shuffle(tips);

Collections.shuffle 返回 void,您不能将 void 分配给 ArrayList

你可以这样做:

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

【讨论】:

    【解决方案2】:

    问题是Collections.shuffle 方法没有返回任何东西。

    你可以试试这个:

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

    【讨论】:

      【解决方案3】:

      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);
      }
      

      【讨论】:

        【解决方案4】:

        Collections.shuffle(tips) 返回无效。所以你不能把它分配给ArrayList()

        你想要的是

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

        【讨论】:

          【解决方案5】:

          你应该这样称呼它:

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

          Collections.shuffle(tips) 直接修改 ArrayList。它不需要创建副本。

          【讨论】:

            【解决方案6】:

            我认为你应该这样写:

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

            另一种方式破坏了将列表设为私有。拥有原始参考的人可以操纵您的私人状态。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2019-11-24
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多