Arrays.sort() and Collections.sort() NullPointerException
While sorting an array by using Arrays.sort() or using Collections.sort() for sorting a list you can encounter a NPE (NullPointerException) . You might be thinking what went wrong ?
So one of element in the array which have been passed for sorting contains the null element. Similar with the list case also .So check for a null entry in your array or list before passing to these methods as parameter.
Example 1 :
String[] strarr={"abc", "def" , null};
Arrays.sort(strarr);
Output 1:
--------
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(String.java:1167)
at java.lang.String.compareTo(String.java:92)
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.sort(Arrays.java:1079)
at Test.main(Test.java:7)
Example 2:
List strlist=new ArrayList();
strlist.add("abc");
strlist.add("def");
strlist.add(null);
Collections.sort(strlist);
Output 2:
----------
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(String.java:1167)
at java.lang.String.compareTo(String.java:92)
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.sort(Arrays.java:1079)
at java.util.Collections.sort(Collections.java:117)
at Test.main(Test.java:13)
Enjoy :)
Brother website for healthcare : http://delighthealthcare.in/
So one of element in the array which have been passed for sorting contains the null element. Similar with the list case also .So check for a null entry in your array or list before passing to these methods as parameter.
Example 1 :
String[] strarr={"abc", "def" , null};
Arrays.sort(strarr);
Output 1:
--------
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(String.java:1167)
at java.lang.String.compareTo(String.java:92)
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.sort(Arrays.java:1079)
at Test.main(Test.java:7)
Example 2:
List
strlist.add("abc");
strlist.add("def");
strlist.add(null);
Collections.sort(strlist);
Output 2:
----------
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(String.java:1167)
at java.lang.String.compareTo(String.java:92)
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.sort(Arrays.java:1079)
at java.util.Collections.sort(Collections.java:117)
at Test.main(Test.java:13)
Enjoy :)
Brother website for healthcare : http://delighthealthcare.in/
Comments
Post a Comment