简体   繁体   中英

Simpler method to autobox / cast a Long to int in java

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?

如果你有一个Long对象,你可以调用intValue()方法来获得一个int

声明你的x是long,而不是long,你可以直接转换为(int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM