【问题标题】:How can I make a list still contain its elements even after clearing it?即使在清除列表后,如何使列表仍然包含其元素?
【发布时间】:2019-10-03 03:04:30
【问题描述】:

我应该如何在 foreach 循环中设置一个列表的键,然后重置上述列表,以便在不清除它的情况下接收其他值。

这是我的代码:

public static Map<String, List<Integer>> trend(Map<String, List<Integer>> companies){
    List<Integer> list = new LinkedList<>();
    List<Integer> list2 = new LinkedList<>();
    Map<String, List<Integer>> finalMap = new HashMap<>();
    int difference = 0;
    for(Map.Entry<String, List<Integer>> entry : companies.entrySet()) {
        list = entry.getValue();
        for(int i = 0; i <= list.size() - 1; i++) {
            if(i < list.size() - 1) {
            difference = list.get(i+1) - list.get(i);
            list2.add(difference);
            }
        }

    finalMap.put(entry.getKey(), list2);
    list.clear();
    list2.clear();
    }
    return finalMap;
}

【问题讨论】:

  • “重置”List 是什么意思?如果您仍然希望 List 包含它的所有元素,为什么要清除它?
  • 这是X Y problem吗?
  • 你不需要 if 在 for 循环中。只需将
  • 我对这个问题的解释很差,但用外行的话来说,我正在遍历地图,因为值是 List 类型的,所以我使用了一个列表来“保存”这些值我可以稍后在我的 for 循环中使用它们。我想将从 for 循环中获得的值分配给一个新地图,但是在完成一个 foreach 循环后,我之前使用的列表中仍然有旧值。本质上我是在问如何在不影响新地图中存储的内容的情况下“清空”列表。

标签: java list dictionary


【解决方案1】:

如果您不想清除该列表,只需删除对该列表的 list.clear() 调用即可。

【讨论】:

    猜你喜欢
    • 2015-08-04
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多