简体   繁体   English

Java 中 ArrayList 内部的 HashMap 被覆盖

[英]HashMap Inside of ArrayList in Java geting Over Write

Suppose I have a String "abca" .假设我有一个字符串"abca" I want to keep track of each alphabet occurrence in every index using HashMap & ArrayList in Java.我想在 Java 中使用 HashMap 和 ArrayList 跟踪每个索引中出现的每个字母。 For example if a=0,b=1,c=2, I want the output like below: for input: abca例如,如果 a=0,b=1,c=2,我想要输出如下:对于输入:abca

[{0=1},{0=1, 1=1},{0=1, 1=1, 2=1},{0=2, 1=1, 2=1}];

I have written this solution in Java:我已经用 Java 编写了这个解决方案:

public static void main(String[] args){
     Scanner in = new Scanner(System.in);

     String x = in.next();
     char a[] = x.toCharArray();
     HashMap<Integer,Integer> hm = new HashMap();
     ArrayList<HashMap<Integer,Integer>> list = new ArrayList();

     for(int i=0;i<a.length;i++){
         if(hm.get((int)a[i]-97)==null){
             hm.put((int)a[i]-97, 1);
         }
         else{
             int pow = hm.get((int)a[i]-97);
             pow++;
             hm.put((int)a[i]-97, pow);
         }
         list.add(hm);
        // System.out.println(list);
     }
     System.out.println(list);
}

But I am getting output as:但我得到的输出为:

[{0=2, 1=1, 2=1}, {0=2, 1=1, 2=1}, {0=2, 1=1, 2=1}, {0=2, 1=1, 2=1}]

At the end of the iteration, ArrayList is updating all the indices of the last stage of HashMap.在迭代结束时,ArrayList 正在更新 HashMap 最后阶段的所有索引。

The original map will be mutated in every iteration, so to fix this you need to create a new HashMap and add it in every iteration.原始映射将在每次迭代中发生变异,因此要解决此问题,您需要创建一个新的HashMap并在每次迭代中添加它。

list.add(new HashMap<>(hm));

output:输出:

[{0=1}, {0=1, 1=1}, {0=1, 1=1, 2=1}, {0=2, 1=1, 2=1}] [{0=1}, {0=1, 1=1}, {0=1, 1=1, 2=1}, {0=2, 1=1, 2=1}]

Well, if you're interested, you can also do it like this.好吧,如果你有兴趣,你也可以这样做。

         Scanner in = new Scanner(System.in);
         String x = in.next();
         char a[] = x.toCharArray();
         List<HashMap<Integer, Integer>> list = new ArrayList<>();
         HashMap<Integer, Integer> hm = new HashMap<>();

         for (char c : a) {
             hm.compute(c-'a', (k,v) -> v == null ? 1 : ++v);
             list.add(new HashMap<>(hm));
         }

         System.out.println(list);

The hm.compute() method looks for the value for the supplied key. hm.compute()方法查找提供的键的值。

  • if null, it initializes to 1.如果为 null,则初始化为 1。
  • otherwise it increments the value by 1否则它将值增加 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM