当前位置:  首页>> 技术小册>> Java语言基础9-常用API和常见算法

1.7.1 ==

  • == 比较的是对象的地址,只有两个字符串变量都指向字符串的常量对象时,才会返回 true 。

  • 示例:

  1. package com.github.string.demo20;
  2. /**
  3. * @author maxiaoke.com
  4. * @version 1.0
  5. *
  6. */
  7. public class Test {
  8. public static void main(String[] args) {
  9. String s1 = "hello";
  10. String s2 = "hello";
  11. System.out.println(s1 == s2); // true
  12. String s3 = new String("hello");
  13. String s4 = new String("hello");
  14. System.out.println(s3 == s4); // false
  15. System.out.println(s1 == s4); // false
  16. }
  17. }

1.7.2 equals() 方法

  • equals() 方法比较的是对象的内容,因为 String 类重写了 equals() 方法,并且 equals() 方法区分大小写:
  1. public boolean equals(Object anObject){}

示例:

  1. package com.github.string.demo21;
  2. /**
  3. * @author maxiaoke.com
  4. * @version 1.0
  5. *
  6. */
  7. public class Test {
  8. public static void main(String[] args) {
  9. String s1 = "hello";
  10. String s2 = "hello";
  11. System.out.println(s1.equals(s2)); // true
  12. String s3 = new String("hello");
  13. String s4 = new String("hello");
  14. System.out.println(s3.equals(s4)); // true
  15. System.out.println(s1.equals(s4)); // true
  16. }
  17. }

1.7.3 equalsIgnoreCase() 方法

  • equalsIgnoreCase() 方法比较的是对象的内容,并且不区分大小写:
  1. public boolean equalsIgnoreCase(String anotherString){}

示例:

  1. package com.github.string.demo22;
  2. /**
  3. * @author maxiaoke.com
  4. * @version 1.0
  5. *
  6. */
  7. public class Test {
  8. public static void main(String[] args) {
  9. String s1 = new String("hello");
  10. String s2 = new String("HELLO");
  11. System.out.println(s1.equalsIgnoreCase(s2)); // true
  12. }
  13. }

1.7.4 compareTo() 方法

  • String 类重写了 Comparable 接口的抽象方法,自然排序,按照字符的 Unicode 编码值进行比较大小,严格区分大小写:
  1. public int compareTo(String anotherString){}

示例:

  1. package com.github.string.demo23;
  2. /**
  3. * @author maxiaoke.com
  4. * @version 1.0
  5. *
  6. */
  7. public class Test {
  8. public static void main(String[] args) {
  9. String s1 = "i";
  10. String s2 = "love";
  11. System.out.println(s1.compareTo(s2)); // -3
  12. }
  13. }

1.7.5 compareToIgnoreCase() 方法

  • compareToIgnoreCase() 方法不区分大小写,其他按照字符的 Unicode 编码值进行比较大小:
  1. public int compareToIgnoreCase(String str){}

示例:

  1. package com.github.string.demo24;
  2. /**
  3. * @author maxiaoke.com
  4. * @version 1.0
  5. *
  6. */
  7. public class Test {
  8. public static void main(String[] args) {
  9. String s1 = new String("hello");
  10. String s2 = new String("Hello");
  11. System.out.println(s1.compareToIgnoreCase(s2)); // 0
  12. }
  13. }

该分类下的相关小册推荐: