0

I've the following code in Java:

void foo(int a) { ... }

void bar() {
    Long x = 42;
    foo(x);  // Compile error: "Method foo(int)   
             // is not applicable for the argument (long)"
    foo((long) x); // Same as before
    foo((int) x); // Compile error: "Cannot cast Long to int"
    foo((int) (long) x);  // OK, but strange and confusing
}

Is there a better way?

Laurent Grégoire
  • 3,866
  • 27
  • 50

2 Answers2

2

If you have a Long object, you can call the intValue() method to get an int.

rgettman
  • 172,063
  • 28
  • 262
  • 343
0

Declare your x as a long, not a Long, and you will be able to cast directly to (int)

codethulhu
  • 3,886
  • 2
  • 19
  • 15