String.equals()方法的实现代码,

通常对String的比较有两种情况,一个是使用==,另一个是使用equals()方法,注意==是对对象的地址进行比较的,而String中的equals()方法是覆盖了Object类的方法,并且实现为对String对象的内容的比较。所以String s1 = new String("hello");String s2 = new String("hello"),我们对s1和s2进行上述比较的时候,前者应该返回false,因为使用new生成的是两个不同的对象。后者应该返回true因为他们的内容是一样的,都是"hello"。那么如果我们还有一个String s3 = "hello";他和s1的比较应该是什么样子的呢,答案是s1==s3为false,equals的比较位true。事实上String类是维持着一个String池的,这个池初始化为空的,当我们String x = "hello"的时候,hello就会被放入这个池中,当我们再次String y = "hello"的时候,他首先去检查池中是否存在一个和hello内容一样的对象,如果存在的话就会把这个引用返回给y,如果不存在的话,就会创建一个并放入到池中。这样就实现了复用。在String有一个方法intern()他可以把String的对象放入到池冲并返回池中的对象。如果我们对s1(String s1 = new String("hello"))调用intern,s1 = s1.intern()这时候,我们再把s1和s3进行“==”的判断,你会发现结果返回true!
看下面的例子

Java代码 复制代码
  1. public class StringTest   
  2. {   
  3.   
  4. public static void main(String[] args)   
  5. {   
  6. String s1 = "hello";   
  7. String s2 = new String("hello");   
  8. String s3 = new String("hello");   
  9.   
  10. testString(s1,s2,s3);   
  11. s2 = s2.intern();   
  12. System.out.println("after s2.intern");   
  13. testString(s1,s2,s3);    
  14.   
  15. }   
  16. private static void testString(String s1,String s2,String s3)   
  17. {   
  18. System.out.println("s1 = s2 is "+(s1==s2));   
  19. System.out.println("s2 = s3 is "+(s2==s3));   
  20. System.out.println("s1.equals(s2) is "+s1.equals(s2));   
  21. System.out.println("s2.equals(s3) is "+s2.equals(s3));   
  22. }   
  23. }  



输出结果为
s1 = s2 is false
s2 = s3 is false
s1.equals(s2) is true
s2.equals(s3) is true
after s2.intern
s1 = s2 is true
s2 = s3 is false
s1.equals(s2) is true
s2.equals(s3) is true

原文地址:https://www.cnblogs.com/3066405538a/p/4909824.html