Java Collections.sort return null when sorting list of strings -
i trying sort list of strings (that contain alphanumeric characters 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 " + tosort.size()); list<string> sorted = collections.sort(tosort); if(sorted == null) { system.out.println("i null , sad."); } else { system.out.println("i not null."); } } } when run get:
tosort size 1 null , sad. why null?
collections.sort() returns void, new collection sorted never initialized.
list<string> sorted = collections.sort(tosort); is like
list<string> sorted = null; collections.sort(tosort); // ^------------> tosort being sorted! to use correctly collections.sort() method must know you sorting same object put in method:
collections.sort(collectiontobesorted); in case:
public class sorterdriver { public static void main(string[] args) { list<string> tosort = new arraylist<string>(); tosort.add("fizzbuzz"); system.out.println("tosort size " + tosort.size()); collections.sort(tosort); if(tosort == null) { system.out.println("i null , sad."); } else { system.out.println("i not null."); } } }
Comments
Post a Comment