简体   繁体   中英

Java Collections.sort return null when sorting list of strings

I am trying to sort a list of strings (that will contain alphanumeric characters as well as punctuation) via Collections.sort :

public class SorterDriver {
    public static void main(String[] args) {
        List<String> toSort = new ArrayList<String>();

        toSort.add("fizzbuzz");
        System.out.println("toSort size is " + toSort.size());

        List<String> sorted = Collections.sort(toSort);
        if(sorted == null) {
            System.out.println("I am null and sad.");
        } else {
            System.out.println("I am not null.");
        }
    }
}

When I run this I get:

toSort size is 1
I am null and sad.

Why null?

Collections.sort() returns a void , so your new collection sorted is never initialized.

List<String> sorted = Collections.sort(toSort);

is like

List<String> sorted = null;
Collections.sort(toSort);    
//                 ^------------> toSort is being sorted!

To use correctly the Collections.sort() method you must know you are sorting the same object you put in the method :

Collections.sort(collectionToBeSorted);

In your case:

public class SorterDriver {
    public static void main(String[] args) {
        List<String> toSort = new ArrayList<String>();

        toSort.add("fizzbuzz");
        System.out.println("toSort size is " + toSort.size());

        Collections.sort(toSort);
        if(toSort == null) {
            System.out.println("I am null and sad.");
        } else {
            System.out.println("I am not null.");
        }
    }
}

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