I have a program that allows user to delete an element from an array and I am trying to sort them in alphabetic order using compareTo(); through a for loop. However, the null values are giving me problems. For example an array with null values:
String[] myArray = {"Apple", "Banana", null, "Durian", null, null, "Grapes"};
When Java is comparing them and reads a null value, it would give me a NullPointerException.
Is there any way that I can sort this array with null values at the back? For example:
{"Apple", "Banana", "Durian", "Grapes", null, null, null}
I know that using Vectors can solve the problem but I am just curious if there is any way that I can just do it without changing my array to vectors.
A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.
If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.
An array value can be non-empty, empty (cardinality zero), or null. The individual elements in the array can be null or not null.
try this
Arrays.sort(myArray, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
return o1.compareTo(o2);
}});
it produces the required order
write your own Comparator
that accepts null values, and pass that comparator to the Arrays.sort(
) method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With