Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting a table with x cols

 
Amit Chandak
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the best data structure in java to represent a table with x cols.
And is there a simple way to sort the table on any one of the cols?
Thanks
Amit
 
Joe Ess
Bartender
Posts: 9256
9
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Amit Chandak:
What is the best data structure in java to represent a table with x cols.

Like all things programming, it depends. javax.swing.table.DefaultTableModel is a good place to start.


And is there a simple way to sort the table on any one of the cols?
Thanks
Amit

javax.swing.table.DefaultTableModel can be set up to use 2d arrays of Objects, and the java.util.Arrays object has lots of sort functionality. . .
 
Vinod Chandana
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Amit Chandak:
What is the best data structure in java to represent a table with x cols.
And is there a simple way to sort the table on any one of the cols?
Thanks
Amit

Try using SortedSet and implementing Comparable interfaces for the objects used to compare.
Regards,
Vinod.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd favor Collections.sort() rather than a SortedSet, as rows may or may not contain duplicate values; we don't necessarily care. And it sounds like you may want to sort on different columns. If you sort on column 1 and then on column 2, the column 1 sort is probably no longer valid; if you're holding on to a SortedSet representing that, you may well be in for confusion. Inside my TableModel I'd have a single List representing all the rows in their current order, and when you want to sort on a particular column, call Collections.sort(List, Comparator) using a Comparator that compares the particular column you wish to sort. Once you sort on column 2, the sort by column 1 is abandoned (unless/until you re-sort it by column 1 again). There are other wayt to do this, simpultaneously maintaining multiple TreeMaps for the various sort orders you may wish to deal with, but this will be somewhat more complex.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic