2

I don't get it; I'm using the DefaultTableModel, and my attempt was this to get the value in a tabel as an int:

Integer.parseInt( tableModel.getValueAt(i, 1) );

Eclipse is saying there is a cast needed from Object to String, so eclipse makes that:

Integer.parseInt( (String) tableModel.getValueAt(i, 1) );

At runtime, the program crashes because it is not possible to cast "int to string". Why? I expected "object -> string -> int".

3
  • 1
    you forgot .toString() Commented Feb 17, 2013 at 13:19
  • 2
    Why would you first convert the Integer to String and then back to Integer? Commented Feb 17, 2013 at 13:28
  • Please edit your question to include an sscce that shows how you add data to your DefaultTableModel and a complete stack trace of any error you encounter. Otherwise respondents can only speculate. Commented Feb 17, 2013 at 16:49

2 Answers 2

4

Try to use:

Integer.parseInt( tableModel.getValueAt(i, 1).toString() );

Just set string representation of the object by using toString().

Sign up to request clarification or add additional context in comments.

1 Comment

Stupid... I thought too much in c/c++, of course my cast did not work.
3

The value you are getting by tableModel.getValueAt(i, 1) already is an Integer. Just cast it appropriately: Integer value = (Integer) tableModel.getValueAt(i, 1); (or int if you want to use the primitive type).

2 Comments

No, tableModel.getValueAt(i, 1) returns an Object by default, per javadoc.
In OPs case it is an Integer. Otherwise he would not get the ClassCastException he describes.

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.