Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic array initialization and sorting question

this is a rather basic java question

I have an array containing String that i want to sort using java.util.Arrays.sort

when i write

String[] myArray = {"A","B","C"};
java.util.Arrays.sort(myArray);

it gets sorted correctly

however when i have

String[] myArray = new String[10];
myArray[0] = "A";
myArray[1] = "B";
myArray[2] = "C";

java.util.Arrays.sort(myArray);

sort throws a nullreferenceexception

i'm pretty sure its something really dumb i just dont get right now. I have to new the String, because hardcoding default values doesnt get anyone, anywhere.

like image 685
Eric Avatar asked Jul 11 '26 04:07

Eric


2 Answers

When you initialize the second array, you only initialize the first three elements. The other elements are initialized to null and thus can't be sorted.

like image 84
Kevin Avatar answered Jul 14 '26 15:07

Kevin


In the source, the method uses compareTo() as a sort condition. Obviously, invoking compareTo() on null, will raise a NullPointerException. As its mentioned in Java Docs that,

All elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array)

Of course here its not about ClassCastException, but invocation of comapreTo() is obvious.

[Edited]

P.S. Figuring this out from Exception Stack Trace is your best bet.

like image 45
Adeel Ansari Avatar answered Jul 14 '26 14:07

Adeel Ansari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!