-2

I get this error java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at line "case 0". why I can't cast Integer to String and how to solve this error ?

@Override
public void setValueAt(Object value, int row, int column) {

    switch (column) {
            case 0: user.get(row).setId(Integer.parseInt((String)value)); break;
            case 1: user.get(row).setUsername((String)value); break;
            case 2: user.get(row).setPassowrd((String)value); break;
            case 3: user.get(row).setEmail((String)value); break;
 
            
    }

    this.fireTableCellUpdated(row, row);
}
Alex Ben
  • 9
  • 2
  • 1
    What do you expect it to do? An integer is a number, and a string is text. They're 2 different things. `Integer.parseInt()` takes an integer and parses it into a string representation of a number. There's no need for any casting here. – Charlie Armstrong Feb 04 '21 at 20:47
  • You can not cast `"Hello"` to an `int`. – Arvind Kumar Avinash Feb 04 '21 at 20:49
  • Charlie Armstrong I am trying to retrieve the user id value from a method which updates the table. I am using Table Model – Alex Ben Feb 04 '21 at 21:04

2 Answers2

0

user.get(row).setId(Integer.parseInt(String.valueOf(value)));

Akif Hadziabdic
  • 2,692
  • 1
  • 14
  • 25
  • This makes no sense at all. If `String.valueOf` converts the object `value` to a `String` such that it can be parsed as an `Integer`, then it must have been an `Integer` to begin with. – WJS Feb 04 '21 at 23:10
  • @WJS - You are spot on! Akif Hadziabdic, if `value` is an `Integer`, you can simply cast it to `Integer`, the way [WJS has done](https://stackoverflow.com/a/66054911/10819573); why do you need to call these two methods unnecessarily? – Arvind Kumar Avinash Feb 05 '21 at 17:38
  • of course, we have to check type in order to improve performances, but if the value is "1" cast will not help because the input is a type of Object – Akif Hadziabdic Feb 08 '21 at 07:47
  • But it isn't a String. Otherwise, (String)value would have worked in the OP's example. Besides, the `ClassCastException` says specifically that value is an Integer. – WJS Feb 08 '21 at 16:51
  • I agree code can be improved, but an input type is an object, the method is public, an instance of class Car ( String toString() { return "Car"}) can be the parameter. – Akif Hadziabdic Feb 09 '21 at 07:41
0

get this error java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at line "case 0"

From the error it looks to me that Object is already an Integer. So just do the following:

user.get(row).setId((Integer)value);

A quick demo:

Object a = 10;
int x = (Integer) a;
System.out.println(x);
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
WJS
  • 36,363
  • 4
  • 24
  • 39