Why Arrays.sort() is sorting other arrays too? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

16th Jun 2021, 5:46 PM
PRATHIK
PRATHIK - avatar
3 Answers
+ 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/
16th Jun 2021, 6:11 PM
ChaoticDawg
ChaoticDawg - avatar
+ 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
17th Jun 2021, 12:49 AM
David Carroll
David Carroll - avatar
+ 3
ChaoticDawg and David Carroll thnx for helping and giving a solution for my question.
17th Jun 2021, 12:58 AM
PRATHIK
PRATHIK - avatar