0
Why Arrays.sort() is sorting other arrays too?
Why Arrays.sort is sorting the array named arr though I am only sorting the temp one in the below code? Code:- import java.util.Arrays; public class Main { public static void main(String[] args) { int arr[] = {1, 5, 2, 3, 7}; int temp[] = arr; Arrays.sort(temp); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); for (int i = 0; i < temp.length; i++) { System.out.print(temp[i] + " "); } } } https://code.sololearn.com/cf8pR9l765PB/?ref=app
3 Antworten
+ 8
PRATHIK It's because you didn't make a copy of the arr, but set temp to point to the same reference as arr. You can use the clone() method and then it should work as expected.
int temp[] = arr.clone();
https://www.geeksforgeeks.org/array-copy-in-java/amp/
+ 4
ChaoticDawg You deserve credit for the right answer.
However, in my mission to discourage usage of or references to GFG articles, I'm providing a much more preferred alternative.
https://www.baeldung.com/java-array-copy
+ 3
ChaoticDawg and David Carroll thnx for helping and giving a solution for my question.