简体   繁体   中英

Behavior of an array after sorting in Java

I want to get some views on the behavior of the following program :

package main;
import java.util.Arrays;
public class StringAnagram {
    public static void main(String args[]) {
        String a = "aabbaabb";
        char[] aArr = a.toCharArray();

        Arrays.sort(aArr); //1
        Arrays.sort(a.toCharArray()); //2

        System.out.println(aArr); // Sorted
        System.out.println(a.toCharArray());  // UnSorted
    }
}

According to me statement 1 sorts the character array referenced by aArr but when it comes to statement 2 the sorting of character array is taking place but somehow the sorted array is not referenced by any variable, so the behavior is lost. Could someone please help me with the same.

Well, let's see what happens.

First, a.toCharArray() is called. This returns a new char array containing the chars "aabbaabb".

Then, this array is sorted.

You didn't give yourself a way to access the array, so you can't. This is what "lost" means here. Nothing special or magic happened, you just made an array you can't access. It's not going to waste memory - the garbage collector will detect that it can't be accessed, and destroy it.

It's similar to if you just did this without the sorting:

a.toCharArray();

Again, toCharArray goes and makes an array for you, and you don't give yourself a way to use it, so it's also "lost". The sorting was a red herring.

Yes. You are right.

Each call to toCharArray() actually creates a new array instance with the characters in the string.

In the case of aArr , you actually refer to the new array instance, you use aArr to sort. Its the array instances referred by the variable aArr which gets sorted.

But when you pass a.toCharArray() to Array.sort() method, you are passing array instance which you don't have a variable referring to. The array instance gets sorted but you don't have any reference.

When you you call println using a.toCharArray() again a new array instance is created and passed to println which is obviously unsorted.

Arrays.sort(a.toCharArray());

This sorts the array returned by a.toCharArray() and not the String a. So whenever you do a.toCharArray() you get a separate(new) Character array of the String. Hence it is unsorted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM