Comparing String and Integer with equals

后端 未结 4 1647
一个人的身影
一个人的身影 2021-01-13 23:02

The output of the below code is false

String str = \"3456\";
String str1 = \"3456\";
System.out.println(Integer.valueOf(str).equals(str1));


        
相关标签:
4条回答
  • 2021-01-13 23:33

    The general contract of the equals() methods states (among other things) that the objects that are being compared need to be of the same class. That's why you'll never be able to compare Apples with Oranges.

    For the full contract of the equals() method, see the javadocs.

    0 讨论(0)
  • 2021-01-13 23:34

    Usually, when implementing equals(), one of the first things to do is to check whether the objects are of one and the same type.

    public boolean equals(Object obj) {
        if (!(obj instanceof SomeType)) return false;
        ...
    }
    

    This is also applied in the Integer and String classes, which answers the question why do you receive false as a result.

    0 讨论(0)
  • 2021-01-13 23:37

    An Integer will never be equal to a String.

    Both classes have very strict equals() definitions that only accept objects of their respective types.

    • Integer.equals():

      The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.

    • String.equals():

      The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

    That's actually a quite common way to implement equals(): only objects of the same class (and occasionally subclasses) can be equal. Other implementations are possible, but are the exception.

    One common exception are the collections such as List: every List implementation that follows the convention will return true when compared to any other implementation, if it has the same content in the same order.

    0 讨论(0)
  • 2021-01-13 23:46

    a Integer Object can't equals with String Object

    use :

    boolean a = str.equals(str1);
    

    OR

    boolean a = (Integer.parseInt(str) == Integer.parseInt(str1));
    
    0 讨论(0)
提交回复
热议问题