Home > Net >  Unable to create new references from existing array. How to do that without using loop?
Unable to create new references from existing array. How to do that without using loop?

Time:06-24

char[] c1 = new char[9];
// Inserted values in c1....      
char[] c2= c1.clone();
Arrays.sort(c1);

We only want to use sort on array c1 and not on array c2.

But above step also sort array c2 based on same references. How to sort c1 and keep c2 unsorted in this case?

CodePudding user response:

Take a look at System#arraycopy. It allows you to copy a subset of the array into another array, which could also be used to entirely clone an array. Example:

char[] c1 = new char[9];
// Inserted values in c1....      
char[] c2 = new char[9]
System.arraycopy(c1, 0, c2, 0, c1.length);

CodePudding user response:

Why do you think c2 gets sorted?

Run this program:

public class App {
    public static void main(String[] args) {
        char[] c1 = new char[] {'a', 'c', 'b'};
        char[] c2 = c1.clone();
        Arrays.sort(c1);
        System.out.println(c1);
        System.out.println(c2);
    }
}

The output is:

abc
acb

CodePudding user response:

Use : Arrays.copyOf() or: System.arraycopy()

  • Related