String str="1234";
String str2="1234";
BigInteger bigInt=new BigInteger("1234");
Object v1=str;
Object v2=str2;
Object v3=bigInt;
System.out.println("Condition1==>>"+v1.equals(v2));
System.out.println("Condition2==>>"+v1.equals(v3));`
Output:
Condition1==>>true
Condition2==>>false
Why the second condition( v1.equals(v3) ) result is false even though the values are same?.What is the difference between two conditions? How to make the second condition result to true?
You might be confused about how types work. Sometimes, there are certain similar (isomporphic) values between two types. For example, the String "123"
and the int 123
. Although they look the same, and can be converted from one to the other without loss of information, they aren't actually the same type (and they have no pre-defined automatic conversion in Java), therefore no two values from each type will be equal.
You have to define and perform those conversions yourself. So you'd need to write:
new BigInteger(v1).equals(v3)
You need to apply equals on the same class objects. So you need to compare String
and String
or BigInteger
and BigInteger
. You can get the String
value of your BigInteger
and compare it with the String
or you need to create a new BigInteger
from the String
and compare it with the other String
.
As @RohitJain commented They are not even the same type. Actually the first check in every equals()
method is
if(other instanceof ThisType)
In your case:
bigInt.toString().equals(str1)
would return true.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.