• Post Reply Bookmark Topic Watch Topic
  • New Topic

unable to sort Object[]  RSS feed

 
sai prasanna
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,

i have a String s= "asd fjs asd fsk fsl fls fhi";
and iam able to sort this String.but when i have a String as follows

"abc xyz sai ram" and iam sorting the String as shown below
and is giving NullPointerException at Arrays.sort
any body please helpme


abc
o[i] = abc
xyz
o[i] = xyz
sai
o[i] = sai
ram
o[i] = ram
before sort
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(Unknown Source)
at java.lang.String.compareTo(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at SortString.main(SortString.java:21)
import java.util.StringTokenizer;
import java.util.Arrays;

public class SortString{
public static void main(String sai[]){

/*String s= "asd fjs asd fsk fsl fls fhi";
char[] c = s.toCharArray();
java.util.Arrays.sort(c);
System.out.println(c);
*/
String[] sa = "abc xyz sai ram ".split("\\s");
Object[] o =new Object[10];

for(int i=0;i<sa.length;i++){
System.out.println(sa[i]);
o[i]=(Object)sa[i];
System.out.println("o[i] = "+o[i]);
}
System.out.println("before sort");
Arrays.sort(o);
System.out.println("after sort");
System.out.println("o = "+o);



}
}

thanks in advance
saiprasanna
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're sorting an array with null entries in it, so you get a NullPointerException. I'm not sure why you're surprised by this. I'm also not sure what the array "o" is for; why not simply sort "sa" directly, which is already the correct size and so will sort without errors?
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not sort sa? Why is o of length 10?
 
sai prasanna
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays.sort(String[]) is not present in the class java.util.Arrays
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A String is an Object.


Try that. See what it prints.
[ May 09, 2006: Message edited by: Paul Sturrock ]
 
sai prasanna
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the reply i was confused
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!