java8之long转int

基本类型long 转int

可以使用java8提供的Math .toIntExact()转换。

long   a = 10;     
 
int b = Math.toIntExact(a);

源码如下

package java.lang;
public final class Math {
    
    
    /**
     * @since 1.8
     */
    public static int toIntExact(long value) {
    
    
        if ((int)value != value) {
    
    
            throw new ArithmeticException("integer overflow");
        }
        return (int)value;
    }

java8以前使用以下方法。

long   a = 10;     
 
int b = (int)a;   

猜你喜欢

转载自blog.csdn.net/fxzzq/article/details/127024246