首先,==有很多限制,如Integer 类型的值在[-128,127] 期间,Integer 用 “==”是可以的(参考),超过范围则不行,那么使用equal则代替则完全ok
public static void main(String[] args) { Long prop=4004L; Long prop1=4004l; Integer prop2=4004; Integer prop3=4004; if(prop2.equals(prop3)){ System.out.println("hi"); }else if(prop2==prop3){ System.out.println("wrong"); } if(prop1.equals(prop2.longValue())){ System.out.println("helloworld"); }else if(prop==prop1){ System.out.println("you are wrong!"); }
返回结果
hi
helloworld
上面的示例说明使用"=="和equal还是有不小的区别的,equal可以替代==
Long源码如下:
/** * Compares this object to the specified object. The result is * <code>true</code> if and only if the argument is not * <code>null</code> and is a <code>Long</code> object that * contains the same <code>long</code> value as this object. * * @param obj the object to compare with. * @return <code>true</code> if the objects are the same; * <code>false</code> otherwise. */ public boolean equals(Object obj) { if (obj instanceof Long) { return value == ((Long)obj).longValue(); } return false; }
Integer源码如下:
/** * Compares this object to the specified object. The result is * <code>true</code> if and only if the argument is not * <code>null</code> and is an <code>Integer</code> object that * contains the same <code>int</code> value as this object. * * @param obj the object to compare with. * @return <code>true</code> if the objects are the same; * <code>false</code> otherwise. */ public boolean equals(Object obj) { if (obj instanceof Integer) { return value == ((Integer)obj).intValue(); } return false; }