在Java中安全地将long转换为int [英] Safely casting long to int in Java

查看:814
本文介绍了在Java中安全地将long转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我目前的实现:

在Java中最常用的方法是验证从long到int的转换没有丢失任何信息?

  public static int safeLongToInt(long l){
int i =(int)l;
if((long)i!= l){
throw new IllegalArgumentException(l +不能转换为int而不更改其值。
}
return i;
}


解决方案

Java 8 来做到这一点。

  import static java.lang.Math.toIntExact; 

long foo = 10L;
int bar = toIntExact(foo);

在溢出时会抛出ArithmeticException。



请参阅: Math.toIntExact(long)



Java 8中添加了其他一些溢出安全的方法。 em>。



示例:




  • Math.incrementExact b $ b
  • Math.subtractExact(long,long)

  • Math.decrementExact(long)

  • Math.negateExact / li>
  • Math.subtractExact(int,int)


What's the most idiomatic way in Java to verify that a cast from long to int did not lose any information?

This is my current implementation:

public static int safeLongToInt(long l) {
    int i = (int)l;
    if ((long)i != l) {
        throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
    }
    return i;
}

解决方案

A new method has been added with Java 8 to do just that.

import static java.lang.Math.toIntExact;

long foo = 10L;
int bar = toIntExact(foo);

Will throw an ArithmeticException in case of overflow.

See: Math.toIntExact(long)

Several other overflow safe methods have been added to Java 8. They end with exact.

Examples:

  • Math.incrementExact(long)
  • Math.subtractExact(long, long)
  • Math.decrementExact(long)
  • Math.negateExact(long),
  • Math.subtractExact(int, int)

这篇关于在Java中安全地将long转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆