【问题标题】:java arraylist<String> seems to overwrite existing items when using the add() method使用 add() 方法时 java arraylist<String> 似乎覆盖了现有项目
【发布时间】:2018-09-04 04:06:54
【问题描述】:

我正在尝试从配置文件中读取行并使用add() 方法将每一行附加到ArrayList 中。

但是,当我通过使用foreach 打印ArrayList 的内容时,它只打印要输入的最后一项。在我看来, add() 方法可能没有正确附加?我还尝试使用 generic for 循环 而不是 foreach,结果仍然相同。

public static void interpret(String line){
    ArrayList<String> rooms = new ArrayList<>(); 
    ArrayList<String> rules = new ArrayList<>(); 

    // Ignore Room and Rule templates
    if(line.contains("(") && line.contains(")")){
        System.out.println("skip"); 
        return;
    }
    if(line.contains("Room;")){
        rooms.add(line);
        rooms.forEach(System.out::println);
    }
    if(line.contains("Rule;")){
        rules.add(line);
        rules.forEach(System.out::println);
    }
}

输出如下。

Rule; (Room: SmartObject, state{condition}, state{condition}, ...)
skip
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Kitchen: Coffee machine, on{time=6}, off{time=12}
Rule; Kitchen: Coffee machine, on{time=6}, off{time=12}

它与读取的文件中的实际文本行混合在一起,但正如您所见,它只打印它上面的行,这是附加到ArrayList 中的最后一行。

它应该看起来像这样。

Rule; (Room: SmartObject, state{condition}, state{condition}, ...)
skip
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Kitchen: Coffee machine, on{time=6}, off{time=12}
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Kitchen: Coffee machine, on{time=6}, off{time=12}

任何帮助/见解将不胜感激。

【问题讨论】:

    标签: java arraylist foreach


    【解决方案1】:

    问题来了:

    ArrayList&lt;String&gt; rules = new ArrayList&lt;&gt;();

    您每次都在创建一个新的 ArrayList,而不是添加到现有的 ArrayList 中

    建议:

    1. 将现有的数组列表传递给您的方法或
    2. 在类级别声明成员变量

    【讨论】:

    • 哦,当然,抱歉,我应该早点看到。感谢您的宝贵时间。
    【解决方案2】:

    使用以下方法签名:

    public static void interpret(List<String> rooms, List<String> rules, String line){
    
        // Ignore Room and Rule templates
        if(line.contains("(") && line.contains(")")){
            System.out.println("skip"); 
            return;
        }
        if(line.contains("Room;")){
            rooms.add(line);
            rooms.forEach(System.out::println);
        }
        if(line.contains("Rule;")){
            rules.add(line);
            rules.forEach(System.out::println);
        }
    
    }
    

    不是每次调用此函数时都创建列表,而是在调用者函数中创建列表并传递给此方法。

    【讨论】:

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