bhylu.com

Advertisements

Java Sort a Copy When the Original Order Matters

Array sorting mutates the array passed to it. Preserve the original sequence when arrival order or a later operation still depends on it.

Understand the idea

Arrays.copyOf creates a separate array container, then Arrays.sort changes that copy. Primitive arrays and object arrays have different sorting overloads, and a comparator applies to appropriate reference-type overloads rather than int[] directly. Choose the representation and ordering rule before selecting an overload.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arrival = {7, 2, 5};
        int[] sorted = Arrays.copyOf(arrival, arrival.length);
        Arrays.sort(sorted);
        System.out.println(Arrays.toString(arrival));
        System.out.println(Arrays.toString(sorted));
    }
}

Expected output

[7, 2, 5]
[2, 5, 7]

The unchanged first output confirms that the mutation happened only to the independent copy. Arrays.toString is a readable diagnostic representation, not a stable general-purpose serialisation format. Sorting the original in place would be a valid different contract if callers did not need its prior order.

Check the official Java documentation for detailed contracts and supported options.