Suppose I have a String "abca"
. I want to keep track of each alphabet occurrence in every index using HashMap & ArrayList in Java. For example if a=0,b=1,c=2, I want the output like below: for input: 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:
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.