【问题标题】:java replace arraylist of stringsjava替换字符串的arraylist
【发布时间】:2016-03-21 02:26:52
【问题描述】:

我似乎不知道如何替换字符串的数组列表。

  ArrayList<String[]> Records

所以在我的 for 循环中,我想替换一条记录,我会一直收到这个错误吗?

ArrayList类型中的set(int, String[])方法不适用于参数(int, String)

        for (int i = 0; i < Records.size(); i++) {
            for (int j = 0; j < 2; j++) {
                if (j == 0) {
                    if(!validateRecords(Records.get(i)[j].toString()))
                    {
                        Logging.info("Records could not be parsed " + Records.get(i)[j].toString());
                        Records.set(j, "CouldNotBeParsed");
                    }else
                    {
                        Logging.info(Records.get(i)[j].toString()+ " has been sanitized");
                    }
                }
            }
        }

使用Records.set() 替换此记录的正确方法是什么?

【问题讨论】:

    标签: java arraylist replace


    【解决方案1】:

    您有一个ArrayListString[],并且您正试图给它一个String。您需要设置内部String[] 的索引,而不是外部ArrayList

    改为这样做:

    Records.get(i)[j] = "CouldNotBeParsed";
    

    【讨论】:

      【解决方案2】:

      由于您不是替换整个数组,而是更改现有数组中的单个条目,因此您需要使用 get() 后跟数组写入,而不是 set()

      if(!validateRecords(Records.get(i)[j].toString())) {
          Logging.info("Records could not be parsed " + Records.get(i)[j]);
          Records.get(i)[j] = "CouldNotBeParsed";
      } else {
          Logging.info(Records.get(i)[j] + " has been sanitized");
      }
      

      请注意,循环内的if (j == 0) 检查看起来非常可疑,因为实际上它使j 上的循环完全无用。你不妨这样写:

      for (int i = 0; i < Records.size(); i++) {
          if(!validateRecords(Records.get(i)[0].toString())) {
              Logging.info("Records could not be parsed " + Records.get(i)[0]);
              Records.get(i)[0] = "CouldNotBeParsed";
          } else {
              Logging.info(Records.get(i)[0] + " has been sanitized");
          }
      }
      

      还请注意,连接字符串时不需要调用toString():Java 编译器会为您插入它们,并为您处理null 值。

      【讨论】:

      • 完美。感谢您的帮助。
      • 最后一个问题。我刚在想。也许我应该在记录中添加另一条记录而不是替换它。那会是什么样子。 Records.add((i)[j] = "notParsed")
      • @user1158745 这就是使用数组的问题——你不能向它们添加项目。如果您想要可以添加记录的内容,请使用ArrayList&lt;ArrayList&lt;String&gt;&gt;。然后你会写Records.get(i).add("notParsed")
      【解决方案3】:

      如果你有一个ArrayList&lt;String[]&gt;,那么它将只包含String 的数组。但是您有以下行:

      Records.set(j, "CouldNotBeParsed");
      

      "CouldNotBeParsed"String,而不是 String[]。如果你真的想要String[],试试这个:

      Records.set(j, new String[]{"CouldNotBeParsed"});
      

      【讨论】:

        猜你喜欢
        • 2021-01-27
        • 2015-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-23
        • 1970-01-01
        • 1970-01-01
        • 2015-05-01
        相关资源
        最近更新 更多