比较Integer对象与int [英] Comparing Integer objects vs int

查看:120
本文介绍了比较Integer对象与int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过在下面将Integer更改为int来修复无限循环:

I fixed an endless loop by changing Integer to int in the following:

public class IntTest {
    public static void main(String[] args) {
        Integer x=-1;
        Integer total=1000;

        while(x != total){
            System.out.println("x =" + x + "total ="+ total);
            x++;
        }
    }
}

什么是正确的理由这个?我认为Integer会比较没有问题。

What is the proper reason for this? I figured Integer would compare no problem.

谢谢。

推荐答案

因为当你制作时!=比较对象时它会比较引用。一般情况下两个对象之间的引用是不同的。

Because when you make != comparing on the object it compares the references. And the references between two objects in general case are different.

比较整数时,它总是比较基元,假设不是引用(没有对象),而是值。

When you compare ints it always compares primitives, lets say not references( there are no objects ), but the values.

因此,如果你想使用Integer,你必须对它们使用equals()。

So, if you want to work with Integer you must use equals() on them.

另外,如果你的值在0到255之间,那么比较由于缓存,整数工作正常。

Additionally, if your values are between 0 and 255 the comparison between Integer works fine, because of caching.

你可以在这里阅读: http://download.oracle.com/javase/tutorial/java/data/numberclasses.html

这篇关于比较Integer对象与int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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