This example shows how you can wrap a table to provide a sorted
view of it. It subclasses
RowPermutedStarTable
,
which is a wrapper that presents its base table with the rows in a
different order.
class SortedStarTable extends RowPermutedStarTable { // Constructs a new table from a base table, sorted on a given column. SortedStarTable( StarTable baseTable, int sortCol ) throws IOException { // Call the superclass constructor - this will throw an exception // if baseTable does not have random access. super( baseTable ); assert baseTable.isRandom(); // Check that the column we are being asked to sort on has // a defined sort order. Class clazz = baseTable.getColumnInfo( sortCol ).getContentClass(); if ( ! Comparable.class.isAssignableFrom( clazz ) ) { throw new IllegalArgumentException( clazz + " not Comparable" ); } // Fill an array with objects which contain both the index of each // row, and the object in the selected column in that row. int nrow = (int) getRowCount(); RowKey[] keys = new RowKey[ nrow ]; for ( int irow = 0; irow < nrow; irow++ ) { Object value = baseTable.getCell( irow, sortCol ); keys[ irow ] = new RowKey( (Comparable) value, irow ); } // Sort the array on the values of the objects in the column; // the row indices will get sorted into the right order too. Arrays.sort( keys ); // Read out the values of the row indices into a permutation array. long[] rowMap = new long[ nrow ]; for ( int irow = 0; irow < nrow; irow++ ) { rowMap[ irow ] = keys[ irow ].index_; } // Finally set the row permutation map of this table to the one // we have just worked out. setRowMap( rowMap ); } // Defines a class (just a structure really) which can hold // a row index and a value (from our selected column). class RowKey implements Comparable { Comparable value_; int index_; RowKey( Comparable value, int index ) { value_ = value; index_ = index; } public int compareTo( Object o ) { RowKey other = (RowKey) o; return this.value_.compareTo( other.value_ ); } } }