警惕long值转化为int,比如在Comparator接口中

3月 2nd, 2016 2,921 留下评论 阅读评论

long值转为int会造成溢出大家都知道,很多时候却会忽视已发bug,造成明明的正值变为了负值(因为int最高位非0,long值大于int最大值2^31-1=2147483647)。

此次出错的地方在使用java.util.Collections.sort中使用Comparator接口中,因为compare方法通过返回int值来比较大小,而逻辑比较大小是通过比较时间戳long值按最近时间排序,一开始不注意就直接把时间戳long值差给直接转为int值返回了,造成了可能的排序错误(有趣的是只需要24天的毫秒值就会超过int的最大值)。

错误代码如下:

Collections.sort(list, new Comparator(){
	@Override
	public int compare(Message o1, Message o2) {
		return (int)(o2.timestamp - o1.timestamp); // wrong
	}
});

显然,我们只要简单的比较2个时间戳long值,返回1和-1即可。

修正代码如下:

Collections.sort(list, new Comparator(){
	@Override
	public int compare(Message o1, Message o2) {
		if(o2.timestamp > o1.timestamp){
			return 1;
		}
		else{
			return -1;
		}
	}
});
Categories: Java 标签:,
  1. 还没有评论呢。