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
  • 4,006
  • 29
  • 52

2 Answers2

2

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

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

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

codethulhu
  • 3,976
  • 2
  • 21
  • 15