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?

2
  • Short answer is Yes. It does affect the "original" array, because you have copied the array reference not the array. Commented Feb 26, 2021 at 1: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. Commented Feb 26, 2021 at 1:50

1 Answer 1

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.
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.