4

I'm writing my own TableModel implementation. As I shall need a few various implementations sharing some functionality, I decided to prepare an abstract class first. The fields of the table are represented by:

protected Object[][] lines;

Basically all elements in the same column should be of the same type, however column classes may vary among different implementations. I would like to write a common setValueAt function in the abstract class, checking whether val is of proper type or not.

@Override
public void setValueAt(Object val, int row, int col) {
    if (val instanceof this.getColumnClass(col))
        lines[col][row] = val;
}

The compiler signals error here:

Syntax error on token "instanceof", == expected

Why?

2
  • 2
    What does the getColumnClass method look like? Commented May 10, 2013 at 13:41
  • Its abstract. What matters is that it gets an int columnIndex argument and returns Class<?> result, as required by TableModel interface. Commented May 10, 2013 at 14:01

2 Answers 2

6

The right operand of instanceof must be a ReferenceType(JLS 15.20). Use

if (this.getColumnClass(col).isInstance(val))
Sign up to request clarification or add additional context in comments.

Comments

2

Rather than using instanceof, you might consider using a generic type in your abstract class. You could declare it with something like:

protected abstract class MyTableModel<T> implements TableModel {
    //...
    protected T[][] lines;
    //...
    @Override
    public void setValueAt(Object val, int row, int col) {
        lines[col][row] = (T) val;
    }
}

This way, you can let Java handle the type checking for the cast.

You could also just write a single generic class, if the only difference between the classes is the type of the values.

4 Comments

Thank you. Your advice is precious, but the point is that lines consists of data of various types. For instance column one is Integer, next is String and so on. In another subclass there could be two Integer columns and no String at all.
Ah. In that case, I'd probably create a generic Column class, and implement TableModel as a wrapper around some type of Collection<Column>. Of course, this is a matter of taste.
Sounds interesting. And what do you think of making my Column a subclass of TableColumn? The model class could then implement TableColumnModel interface as well, preventing any possible data conflicts between TableModel and TableColumnModel.
I haven't really looked at TableModel -- I don't do much gui -- so I can't really say.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.