dazhi2010 2017-07-13 06:02 采纳率: 0%
浏览 9914

关于Java的Byte和Integer的equals及==对比方式的问题

Byte a = 1;
Byte b = new Byte("1");
Byte c = 0x1;
System.out.println(a.equals(1));
System.out.println(a==1);
System.out.println(a.equals(b));
System.out.println(a==b);
System.out.println(c.equals(1));
System.out.println(c==1);
System.out.println("======================");
Integer i = 1;
System.out.println(i.equals(1));
System.out.println(i==1);


图片说明

如上面的代码,为什么Byte的equals不能直接跟1比?比较结果为false;而Integer却可以?

  • 写回答

4条回答

  • 缺舟丶一帆渡 2017-07-13 06:13
    关注

    /**
    * Compares this object to the specified object. The result is
    * {@code true} if and only if the argument is not
    * {@code null} and is an {@code Integer} object that
    * contains the same {@code int} value as this object.
    *
    * @param obj the object to compare with.
    * @return {@code true} if the objects are the same;
    * {@code false} otherwise.
    */
    public boolean equals(Object obj) {
    if (obj instanceof Integer) {
    return value == ((Integer)obj).intValue();
    }
    return false;
    }

           * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    
           /**
     * Compares this object to the specified object.  The result is
     * {@code true} if and only if the argument is not
     * {@code null} and is a {@code Byte} object that
     * contains the same {@code byte} value as this object.
     *
     * @param obj       the object to compare with
     * @return          {@code true} if the objects are the same;
     *                  {@code false} otherwise.
     */
    public boolean equals(Object obj) {
        if (obj instanceof Byte) {
            return value == ((Byte)obj).byteValue();
        }
        return false;
    }
    
        Integer的equals方法是转为int类型 ,Byte的equals是byte类型  ,1是int类型
    
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建