java - Collection.sort Not Returning Expected Result -
i trying determine order of columns in mysql database in java. have create statement(this.create) of table , name of columns (column.getname()). find index of column name in create statement. assign these values list, , then, sort them using collectio.sort(). isthen used determine order of columns. issue not getting expected result. here code:
public void ordercolumns() { list<integer> cols = new arraylist(); ( column column : columns ) { cols.add( this.create.indexof( "`" + column.getname() + "`")); } collections.sort( cols ); ( column column : columns ) { ( int = 0; < cols.size(); i++) { if ( this.create.indexof( "`" + column.getname() + "`") == cols.get( )) { this.order_of_columns.add( column ); } } } system.out.println(this.create); for( column column : order_of_columns ) { system.out.println( this.name + " : " + this.create.indexof( "`" + column.getname() + "`") + " " + column.getname()); } }
here output 1 table:
create table `versions` ( `id` int(11) unsigned not null auto_increment, `name` varchar(50) not null default '', `version` varchar(10) not null default '', primary key (`id`) ) engine=innodb auto_increment=12 default charset=latin1; versions : 77 name versions : 119 version versions : 28 id
any ideas of doing wrong? thank help!
the sort
working fine, you're not using order sort produced. after sort
, here's do:
( column column : columns ) { ( int = 0; < cols.size(); i++) { if ( this.create.indexof( "`" + column.getname() + "`") == cols.get( )) { this.order_of_columns.add( column ); } } }
that is, go through columns in original order. each column, go through cols
see if indexof
result in cols
array. purpose, order of elements in cols
array won't matter, since you're doing checking see whether index somewhere in array. you're adding things order_of_columns
in same order appear in columns
. haven't rearranged anything, , sort
useless.
however, if go through cols
first, you'll adding order_of_columns
based on order in cols
. therefore, think if switch 2 for
's, you'll answer want.
there better ways this, though. code doing lot of duplicate work sorting integers, , going through , figuring out columns correspond integers--work you've done. better create pojo class columnandindex
has integer
, column
, , make comparable
class compareto()
compares integer (which indexof
value). instead of list<integer>
, create list<columnandindex>
stores both column
, index. use sort
on that; sort on indexes. go through result, , columns there--no work needed.
Comments
Post a Comment