Unexpected output when creating a List of Lists in Java

You are adding all the integers to the same inner list (the one that you create at the start of your method with the statement List<Integer> l1 = new ArrayList<Integer>();).

You should create a new List before adding elements to it:

for(int i=1; i<n; i++) {
    if(S.charAt(i)==S.charAt(i-1)) {
        count++;
    } else {
        i2 = i-1;
        if(count>=3) {
            List<Integer> l1 = new ArrayList<Integer>();
            l1.add(i1);
            l1.add(i2);
            l2.add(l1);
        }

        count =1;
        i1=i;
    }
}

Leave a Comment