• Post Reply Bookmark Topic Watch Topic
  • New Topic

alternative method for Arrays.sort(Object a[])  RSS feed

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Arrays.sort(Object a[]), this method doing sorting by comparing Strings.
but in my case i have some normal Strings and some strings with number as first 3 letters like
2 ijk
1 abc
3 abcdf
.
.
.
.
10 asdf
11 xyz
9 pqr


the above all are not yet sorted

what happens is after sorting it is printing like

1 abc
10 asdf
11 xyz
2 ijk
3 abcdf
.
.
.
9 pqr
but my requirement is like

1 abc
2 ijk
3 abcdf
.
.
.
.
9 pqr
10 asdf
11 xyz

could any one suggest me a method which compares integers first and then strings that fulfil my requirement.
 
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't have any integers in your array. You only have Strings. And to the computer a String starting with "10" comes before "1 ". That is what the computer thinks its "natural order" is, and that's that.

Now if you have "10" and "01", that would be different.

You can't have two kinds of member in an array, [but you can have Object[] arrays which contain different subclasses of Object.]

Look up the Arrays.sort methods and find out what the requirements of their arguments are.

Try making a new type of class like NumberAndName.
Try splitting the String and analysing the number component.

See how far you can get with that sort of approach and tell us whether it worked.

CR
 
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could also use Arrays.sort(T[] a, Comparator<? super T> c). You'll need to create your own comparator to compare the strings the way you want.

Yuriy
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!