compareTo与equals与==

    技术2022-05-20  35

    今天看到程序里面比较字符串是不是相等,用到的是:str1.compareTo(str2)==0,刚开始还真不习惯,一直是用equals来比较字符串的,

    在java.long包下的简单数据类Byte、Character、Float、Integer、Short、Long、Boolean、String中都有这个方法

    第一种解释:在数字上比较两个 [Byte][Character][Float][Integer][Short][Long] 对象。   对应Byte、Character、Float、Integer、Short、Long来说的

    Char类型:int compareTo(Character anotherCharacter)根据数字比较两个Character对象

    第二种解释:将此Boolean实例与其他实例进行比较。仅对于boolean类型的对象来说的

    Boolean类型:int compareTo(Boolean b)将此Boolean实例与其他实例进行比较

    第三种解释:按字典顺序比较两个字符串。仅对String类型的对象来说的

    String类型:int compareTo(String anotherString)按字典顺序比较两个字符串

    public class CompareToTest extends AndroidTestCase{ public void testCompareTo() { String str1=new String("abc"); String str2=new String("abc"); if (str1.compareTo(str2)==0) { System.out.println("str1 equals str2"); } } } 

    打印的是:str1 equals str2

     


    最新回复(0)