[英]How to compare values between string and BigInteger in java
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? 为什么第二个条件(v1.equals(v3))的结果即使为相同也为假?两个条件有什么区别? 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
. 例如,字符串"123"
和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. 尽管它们看起来相同,并且可以在不损失信息的情况下从一个转换为另一个,但是它们实际上不是同一类型(并且在Java中没有预定义的自动转换),因此每种类型都不会有两个值等于。
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. 您需要在相同的类对象上应用equals。 So you need to compare String
and String
or BigInteger
and BigInteger
. 因此,您需要比较String
和String
或BigInteger
和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
. 您可以获取BigInteger
的String
值并将其与String
进行比较,或者需要从String
创建一个新的BigInteger
并将其与其他String
进行比较。
As @RohitJain commented They are not even the same type. 正如@RohitJain所评论的,它们甚至不是同一类型。 Actually the first check in every equals()
method is 实际上,每个equals()
方法中的第一个检查是
if(other instanceof ThisType)
In your case: 在您的情况下:
bigInt.toString().equals(str1)
would return true. 将返回true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.