Reputation: 19863
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.
Upvotes: 2
Views: 2627
Reputation: 1
An array list should be used because there are 3 elements not 10.
The other 7 elements of the array will have a null value.
It is these null values that cause the Null Pointer issue when sorting.
Upvotes: -1
Reputation: 533530
try the following to sort just the first three elements.
Arrays.sort(myArray, 0, 3);
Upvotes: 3
Reputation: 39907
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.
Upvotes: 3
Reputation: 6831
It cant work on null strings which are there when you initially create the Array. To avoid either explicitly make all as "" or else assign as much as require.
Although dont know whether this is a miss at API level as they could have catered for the null object (the way we get in SQL orderby) or is there something more to it.
Upvotes: 1
Reputation: 32730
The array has 10 items, but you only put 3 inside. So, the other 7 are NULL. Consider using a ArrayList instead.
Upvotes: 0
Reputation: 10987
You defining the array size by 10 but only initializing 3 indexes. Change your array size to 3 or initialize all ten.
Upvotes: 0
Reputation: 143144
I think that since you make myArray
store 10 elements, it's (effectively) adding 7 nulls to the end, and then Arrays.sort()
can't sort a null element against a string.
Upvotes: 1
Reputation: 89749
What happens is that when you have the array that has ten items, the other items are uninitialized. So when the sort algorithm works, it tries to take the value of the string, but instead gets nothing, and throws the exception.
You need to make sure that you don't try to sort an array that has more space than things you place into it.
Upvotes: 1
Reputation: 30439
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.
Upvotes: 7