Java8_131 rt包源码阅读记录

java.lang.String源码分析

2019-12-05  本文已影响0人  Oliver_Li
  1. 描述
  1. 构造函数
 public String(String original) {
     this.value = original.value;
     this.hash = original.hash;
 }

 public String(char value[]) {
     this.value = Arrays.copyOf(value, value.length);
 }
   
 String(char[] value, boolean share) {
     this.value = value;
 }
  1. isEmpty()
 public boolean isEmpty() {
      return value.length == 0;
  }
  1. equals(Object anObject)、equalsIgnoreCase(String anotherString)
     public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
  1. hashCode()
 public int hashCode() {
       int h = hash;
       if (h == 0 && value.length > 0) {
           char val[] = value;

           for (int i = 0; i < value.length; i++) {
               h = 31 * h + val[i];
           }
           hash = h;
       }
       return h;
   }
  1. charAt(int index)
  1. split(String regex)、split(String regex, int limit)
  1. replace(CharSequence target, CharSequence replacement)
  1. intern()
  1. 字符串对象的创建
  1. 对象创建测试
String a = "呵呵";            
String a1 = "呵" + "呵";      
String a2 = new String("呵呵");
String a3 = a2.intern();    
---------------------------------------------------------------------------
String s = new String("嘻嘻");  
String s1 = "嘻嘻";            
String s3 = s.intern();
---------------------------------------------------------------------------
String s4 = new String("嘻嘻");  
String s5 = s.intern();        
String s6 = "嘻嘻";             
String o = "嘻嘻";
String b = new String("嘻嘻");            
String d = new String("嘻") + new String("嘻");
String e = "嘻" + new String("嘻");   
String h = new StringBuilder("嘻").append("嘻").toString();
String s4 = new String("嘻") + new String("嘻");    
String s5 = "嘻嘻";                                 
String s6 = s4.intern();
------------------------------------------------------------------------------
String s7 = new String("嘻") + new String("嘻");    
String s8 = s7.intern();    
String s9 = "嘻嘻";   
  1. String为什么不可变

结语:对象生成测试大多数是根据代码现象、网上资料推测出来的难免有疏漏,欢迎指正!

上一篇下一篇

猜你喜欢

热点阅读