java中(equals与==)- 笔记

1.看== 和equals的区别:(String 类中重载了equals方法!)

前者比较引用,后者则比较对象中真正的值

 1 package test;
 2 import org.omg.CORBA.Object;
 3 public class hello {        
 4     public static void main(String []args)
 5     {
 6         String s1=new String("cisco");
 7         String s2=new String("cisco");
 8         System.out.println(s1==s2);
 9         System.out.println(s1.equals(s2));
10     }
11  }
false
true



2.
1
package test; 2 import org.omg.CORBA.Object; 3 public class hello { 4 public static void main(String []args) 5 { 6 String s1="cisco"; 7 String s2="cisco"; 8 System.out.println(s1==s2); 9 System.out.println(s1.equals(s2)); 10 } 11 }
true
true

 是一个典型的flyweight 模式在字符串对象创建中的应用。这个模式通过减少对象的创建来节约内存。String对象会创建一个字符串池(a pool of string),如果当前准备新创建的字符串对象的值在这个池子中已经存在,那么就不会生成新对象,而是复用池中已有的字符串对象。flyweight 模式的精髓就是对象复用。不过,只有采用String s = “Hello”方式(而非用”new“关键字)声明String对象的时候这个规则才会被应用。

Coding
原文地址:https://www.cnblogs.com/ccie-leon-43093/p/5373412.html