Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, August 14, 2008

Java 5 Enums rule!

After reading a section from my new Effective Java 2nd edition book I realized that I was using the new Enums incorrectly. I was using the ordinal when I should have been using the EnumMap type to map/reference variables assigned to each enum. An example would explain better.

public enum StatusType {
READY(true),
HOLDING(false),
HOLD_NOW(false);

public final boolean warnClient;

StatusType(boolean warn)
{
warnClient = warn;
}
};

Previously I was doing something like this:

ArrayList warnings = new ArrayList(StatusType.values().length);
for(StatusType type: StatusType.values())
{
warnings.add(type.warnClient);
}

and to access that I'd do:

for(StatusType type: StatusType.values())
{
boolean warn = warnings.get(type.ordinal());
something.enable(warn);
}

This is not great for a number of reasons, and the better implementation is to use an equally efficient EnumMap like so:

EnumMap map = new EnumMap(StatusType.class);

for( StatusType type: StatusType.values())
{
map.set(type, type.warn);
}

and then to access

for( StatusType type: StatusType.values())
{
boolean warn = map.get(type);
something.setEnabled(warn);
}

Using an EnumMap is much safer than using an ArrayList as it is fairly easy to overrun the ArrayList unless you know to use the .ordinal() so it's much less safe than using enum values as in the EnumMap method. Also, the ordinal() call isn't supposed to be used by developers using Java.

Thursday, September 20, 2007

Today I struggled with sorting columns in a JTable in Java 1.6. I wanted to have an underlying object (called job) which corresponded with a table Row. At first I created my own JobTableModel which implemented AbstractTableModel. This worked great until I tried to use table sorters. The underlying ArrayList containing my Job objects were synced up with the the row that represented them, so when you sorted the rows got jumbled compared to their corresponding job objects.

To solve this problem I decided to just keep my list of job objects unsorted, and just search the list based on a value in the table which would match one of the variables in the job object. This worked great until I sorted a column; which utterly confused me. Apparently, when you use JTable.getSelectedRow it still doesn't match up with the underlying table model. Instead you have to make this call to get the actual row that was clicked!
int selected=_tJobs.convertRowIndexToMode(_tJobs.getSelectedRow());

Phew, now everything works great! Thank you Java for adding RowSorting with JTables!

Buy Prints

  © Blogger template 'Photoblog II' by Ourblogtemplates.com 2008

Back to TOP