zoukankan      html  css  js  c++  java
  • String创建对象的难题一

    /**
     * 如何保证变量s指向的是字符串常量池中的数据呢?
     * 有两种方式:
     * 方式一: String s = "shkstart";//字面量定义的方式
     * 方式二: 调用intern()
     *         String s = new String("shkstart").intern();
     *         String s = new StringBuilder("shkstart").toString().intern();
     *
     */
    public class StringIntern {
        public static void main(String[] args) {
    
            String s = new String("1");
            s.intern();//调用此方法之前,字符串常量池中已经存在了"1"
            String s2 = "1";
            System.out.println(s == s2);//jdk6:false   jdk7/8:false
    
    
            String s3 = new String("1") + new String("1");//s3变量记录的地址为:new String("11")
            //执行完上一行代码以后,字符串常量池中,是否存在"11"呢?答案:不存在!!
            s3.intern();//在字符串常量池中生成"11"。如何理解:jdk6:创建了一个新的对象"11",也就有新的地址。
                                                //         jdk7:此时常量中并没有创建"11",而是创建一个指向堆空间中new String("11")的地址
            String s4 = "11";//s4变量记录的地址:使用的是上一行代码代码执行时,在常量池中生成的"11"的地址
            System.out.println(s3 == s4);//jdk6:false  jdk7/8:true
        }
    
    
    }
  • 相关阅读:
    几种常用的曲线
    0188. Best Time to Buy and Sell Stock IV (H)
    0074. Search a 2D Matrix (M)
    0189. Rotate Array (E)
    0148. Sort List (M)
    0859. Buddy Strings (E)
    0316. Remove Duplicate Letters (M)
    0452. Minimum Number of Arrows to Burst Balloons (M)
    0449. Serialize and Deserialize BST (M)
    0704. Binary Search (E)
  • 原文地址:https://www.cnblogs.com/zyf-yxm/p/13663980.html
Copyright © 2011-2022 走看看