Arraylist outputs duplicate

Viewed 69

I am making a sorting program using bubble sort. I want to display what the array looks like each iteration, so if the input is [5,4,3,2,1] I want it to display [4, 3, 2, 1, 5] in the first iteration

public static void main(String[] args) {
    Integer[] age = {5,4,3,2,1};
    //int[][] ef = new int[age.length][];
    ArrayList<Integer[]> fe = new ArrayList<Integer[]>();
    
    for(int i=0;i<2;i++)
    {
        for(int ii=1;ii<5;ii++)
        {
            //System.out.println(Arrays.toString(age));
            if(age[ii]<age[ii-1])
            {
                int x = age[ii];                    
                age[ii]=age[ii-1];
                age[ii-1]=x;
            }
        }
        
        System.out.println("result "+Arrays.toString(age)+"\n");
        fe.add(age);                            
    }
    //System.out.println(Arrays.toString(age));
    for(Integer[] f : fe)
    {
        System.out.print(Arrays.toString(f));
    }
}

The output i want is [4, 3, 2, 1, 5][3, 2, 1, 4, 5]

Instead I get [3, 2, 1, 4, 5][3, 2, 1, 4, 5]

2 Answers

You need to make a copy of the array instead of adding the same reference multiple times.

fe.add(age.clone());

Your algorithm modifies age in place - you never create a copy of the array. In Java, any non-primitive is not stored by value but by reference, so fe contains several references to the same array.

Related