String類源碼學習

來源:互聯網
上載者:User

/** Cache the hash code for the string */

    private int hash; // Default to 0

//String類將hashCode()的結果緩衝為hash值,提高效能。 從這裡可知:String的hash值是從0開始算的,然後根據字元數組計算出來

//equals方法實現方式

//String對象equals()相等的條件是二者同為String對象,長度相同,且字串值完全相同;不要求二者是同一個對象。
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;
    }

//這裡可以看出來String值的hash值的計算方法
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;
    }


//String str=new string("str");這種方式構造出來的字串和單獨的字面量"str"一定相等的,因為他們的值以及hash值都是相等的
public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }
    
測試類別
import org.junit.Test;


public class test
{
    Object obj=new Object();
    String str=new String("123");
    @Test
    public void test(){
      System.out.println(obj.hashCode());  
      System.out.println("\"123\".hashCode():"+"123".hashCode());
      System.out.println(str.hashCode());
      int h=0;
      for(int i=0;i<"123".length();i++){
          char [] val="123".toCharArray();
          h=h*31+val[i];
      }
      System.out.println("h:"+h);
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.