直接上问题模拟和总结:
import java.io.*; public class Main { public static void main(String[] args) { String a = "abc"; String b = "abc"; String c = null; System.out.println(a == b); a = new String("abc"); b = new String("abc"); System.out.println(a == b); //将"abc"序列化在字节数组中 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { ObjectOutputStream outt = new ObjectOutputStream(byteArrayOutputStream); outt.writeObject("abc"); outt.writeObject("abc"); } catch (IOException e) { e.printStackTrace(); } //从字节数组中反序列化"abc" ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); try { ObjectInputStream inn = new ObjectInputStream(byteArrayInputStream); b = (String) inn.readObject(); c = (String) inn.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println(a == b); System.out.println(a.equals(b)); a = c; System.out.println(a == b); //将"abc"序列化在字节数组中 ByteArrayOutputStream byteArrayOutputStream1 = new ByteArrayOutputStream(); try { ObjectOutputStream outt = new ObjectOutputStream(byteArrayOutputStream1); outt.writeObject("abc"); } catch (IOException e) { e.printStackTrace(); } //从字节数组中反序列化"abc" ByteArrayInputStream byteArrayInputStream1 = new ByteArrayInputStream(byteArrayOutputStream1.toByteArray()); try { ObjectInputStream inn = new ObjectInputStream(byteArrayInputStream1); a = (String) inn.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println(a == b); } }
结果:
总结:
1、String对象通过""创建时,统一指向方法区中的运行时常量池,所以内容相同时,地址也相同
2、String对象通过new创建(禁止,浪费性能),会先在常量池创建常量,然后在堆中创建对象,两个对象内容相同地址不同,共建三个对象
后面这几条为推测,若有大神,跪求指点:
3、反序列化得的String对象创建在堆里,跟常量池中对象比较时,出现内容相同,地址不同的情况
4、同一个源反序列化得到的具备相同内容的String对象,地址也相同。(求解原因)
5、不同源反序列化得到的具备相同内容的String对象,地址不同。(求解原因)