How do I compare strings in Java?

1. 语法知识

  • ==:判断的是引用的相等性(reference equality),也即是否为同一对象;
  • .equals():判断的是值的相等性(value equality),也即是否在逻辑上相等;

2. 举例

  • new String(“test”).equals(“test”) // –> true
    • // These two have the same value
  • new String(“test”) == “test” // –> false
    • // … but they are not the same object
    • new String(“test”) == new String(“test”) // –> false
  • “test” == “test” // –> true
    • literals are interned by the compiler and thus refer to the same object
  • Objects.equals(“test”, new String(“test”)) // –> true
    • Objects.equals(null, “test”) // –> false
    • // … but you should really just call Objects.equals()
posted on 2017-07-25 22:53  未雨愁眸  阅读(183)  评论(0编辑  收藏  举报