0

I do not understand why arrSort gets sorted too even if I did not declare it to be sorted?

arrSort1 = arrSort does not mean arrSort = arrSort1 right?

public static void main(String[] args) {
    int[] arrSort = {4024, 4209, 9254, 8996, 9017, 6679, 3412, 6546, 2682, 42};
    int[] arrSort1 = arrSort;
    displayArray(arrSort);
    displaySorted(arrSort1);
    displayArray(arrSort);
}
public static void displayArray(int[] arrList){
    for(int i = 0; i < arrList.length; i++)
        System.out.print(arrList[i] + " ");
    System.out.println();
}
public static void displaySorted(int[] arrSort1){
    Arrays.sort(arrSort1);
    for(int i = 0; i < arrSort1.length; i++){
        System.out.print(arrSort1[i] + " ");    
    }
    System.out.println();
}

The output says

4024 4209 9254 8996 9017 6679 3412 6546 2682 42 
42 2682 3412 4024 4209 6546 6679 8996 9017 9254 
42 2682 3412 4024 4209 6546 6679 8996 9017 9254 

2 Answers 2

1

Both arrSort1 and arrSort are referencing the same array hence the outcome, you might want to use Arrays.copyOf.

Example:

int[] arrSort1 = Arrays.copyOf(arrSort,arrSort.length);
Sign up to request clarification or add additional context in comments.

Comments

0

It's the same with pointer in C++, You are assign arrSort1 = arrSort then they are point to the same place in memory. When you do some thing with one then the other will change too. You may try to new it before assign

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.