Peg*_*gah 0 java arrays comparison integer
我想比较两个Integer类型数组的值.当我比较它们的确切值时,我得到了错误的答案,当我将它们与Arrays.equals进行比较时得到了正确的答案:
Integer a[]=new Integer[2];
Integer b[]=new Integer[2];
a[0]=138;
a[1]=0;
b[0]=138;
b[1]=0;
boolean c;
c=a[0]==b[0];//c is false
c=Integer.valueOf(a[0])==Integer.valueOf(b[0]);//c is false
c=Arrays.equals(a, b);//c is true
Run Code Online (Sandbox Code Playgroud)
你正在寻找intValue,而不是Integer.valueOf(虽然很容易看到你如何让他们感到困惑!):
c = a[0].intValue() == b[0].intValue();
Run Code Online (Sandbox Code Playgroud)
Java有原始类型(int,byte,double,等),也引用类型(对象),对应于他们那些你需要一个对象的情况.您的代码正在a[0] = 138;自动装箱Integer实例内的原始值138 .
intValue返回实例int包含的原语Integer.Integer.valueOf用于获取Integer实例(从一个int或一个String - 在您的情况下,它将valueOf(int)通过自动解除您的Integer参考使用).
你也可以这样做:
c = (int)a[0] == (int)b[0];
Run Code Online (Sandbox Code Playgroud)
...将触发自动拆箱.
有关拳击(包括自动装箱和拆箱)的更多信息,请参阅规范.
| 归档时间: |
|
| 查看次数: |
3271 次 |
| 最近记录: |