• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting two dimensional array

 
Vic Newman
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to sort a 2 dimensional array with Arrays.sort()? It works great with a one dimensional array. I have a simple 2 dimensional array of strings [5] [10]. I want to sort on the first element.
 
Neil Laurance
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think you can directly use sort, but someting like this should be a good starting point:

According to my Java in a Nutshell, in most cases the Comparator.compare method should be implemented to return 0 only when o1.equals(o2) returns true. My example doesn't abide by that rule, so there may be a better way to sort this...
Cheers, Neil
 
Tom Hughes
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a simple way to implement the equals method would be

I often do this with Comparators, it is not the most efficient but it is good enough 99% of cases.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Neil Laurance:
I don't think you can directly use sort[...]

You can - there is also an Array.sort method that gets a Comparator.
 
Andrew Lit
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
i would be appreciated if someone explained me what this line means and what it does?
also how it is concerned with the array, which you want to sort?

thanx
 
Neil Laurance
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:
You can - there is also an Array.sort method that gets a Comparator.

In that case, you can use:

Cheers, Neil
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic