0

Here is the code block I am referring:

public class ExtraCandies
{
    public static void main(String[] args)
    {
        int[] candies = {2,3,5,1,3};

        int temp = 0;
        List<Boolean> isGreatestPossibleList = new ArrayList<>();
        int[] tempArray = candies;

        Arrays.sort(tempArray);

        //Here the debugger shows both tempArray and candies array as sorted.
    }
}

When I debug this code, I get that the tempArray gets sorted just fine. And the tempArray becomes {1,2,3,3,5}. But the debugger now also shows the candies array got sorted. I am confused how can this be? Shouldn't the sort method only sort the tempArray here?

SteroidKing666
  • 553
  • 5
  • 13
  • Short answer is Yes. It does affect the "original" array, because you have copied the array *reference* not the array. – Stephen C Feb 26 '21 at 01:43
  • I have a dup-closed this as a dup of a question that explains what assigning one array variable to another actually does. What you are seeing is a direct consequence of that. – Stephen C Feb 26 '21 at 01:50

1 Answers1

1

Assigning an array to another array is not actually duplicating it - you are just setting the reference of the original array to the new one. Sorting the array would mean sorting the reference, thus sorting both arrays.

You'll want to use a for loop, or Arrays.copyOf(array, length)

public class ExtraCandies
{
    public static void main(String[] args)
    {
        int[] candies = {2,3,5,1,3};

        int temp = 0;
        List<Boolean> isGreatestPossibleList = new ArrayList<>();
        int[] tempArray = Arrays.copyOf(candies, candies.length);

        Arrays.sort(tempArray);

        //Here the debugger shows both tempArray and candies array as sorted.
    }
}
Spectric
  • 30,714
  • 6
  • 20
  • 43