美文网首页
2018-10-23Java的“==”、“equals”和“co

2018-10-23Java的“==”、“equals”和“co

作者: Felixxin | 来源:发表于2018-10-23 14:25 被阅读0次

    字符串的比较函数

    我们可以用“==”来比较字符串吗取决于我们使用的语言是否支持运算符重载
    Java语言可能无法使用“==”来比较两个字符串。
    在使用“==”的时候,实际上会比较这两个对象是否是同一个对象。

    // "static void main" must be defined in a public class.
    public class Test {
        public static void main(String[] args) {
            // initialize
            String s1 = "Hello World";
            System.out.println("s1 is \"" + s1 + "\"");
            String s2 = s1;
            System.out.println("s2 is another reference to s1.");
            String s3 = new String(s1);
            System.out.println("s3 is a copy of s1.");
            // compare using '=='
            System.out.println("Compared by '==':");
            // true since string is immutable and s1 is binded to "Hello World"
            System.out.println("s1 and \"Hello World\": " + (s1 == "Hello World"));
            // true since s1 and s2 is the reference of the same object
            System.out.println("s1 and s2: " + (s1 == s2));
            // false since s3 is refered to another new object
            System.out.println("s1 and s3: " + (s1 == s3));
            // compare using 'equals'
            System.out.println("Compared by 'equals':");
            System.out.println("s1 and \"Hello World\": " + s1.equals("Hello World"));
            System.out.println("s1 and s2: " + s1.equals(s2));
            System.out.println("s1 and s3: " + s1.equals(s3));
            // compare using 'compareTo'
            System.out.println("Compared by 'compareTo':");
            System.out.println("s1 and \"Hello World\": " + (s1.compareTo("Hello World") == 0));
            System.out.println("s1 and s2: " + (s1.compareTo(s2) == 0));
            System.out.println("s1 and s3: " + (s1.compareTo(s3) == 0));
        }
    }
    

    通过上述代码可以看出比较字符串使用“equals”和“compareTo”一定没有问题。使用“==”的时候要谨慎。

    相关文章

      网友评论

          本文标题:2018-10-23Java的“==”、“equals”和“co

          本文链接:https://www.haomeiwen.com/subject/wrfazftx.html