Java 中字串與 []byte 位元組數組

來源:互聯網
上載者:User

標籤:重載   lis   contains   index   情況   code   原因   本質   har   

一、字串

1. +=  重載符號 與 concat

str1 += str2 :底層用的 StringBuilder 效率更高,但是不夠靈活,在某些情況下效率反而較低。

str1 = new StringBuilder().append(str1).append(str2).toString();

concat:返回一個新的字串,在字串很少時,效率稍高。

StringBuilder:使用 append 拼接,在多段字串拼接時效率高。

@org.junit.Testpublic void test() {    int times = 100000;    String s1 = "";    String s2 = "";    StringBuilder s3 = new StringBuilder("");    long a = System.currentTimeMillis();    for(int i = 0 ;i < times ; i ++){        s1 += "a";    }    long b = System.currentTimeMillis();    for(int i = 0 ;i < times ; i ++){        s2 = s2.concat("a");    }    long c = System.currentTimeMillis();    for(int i = 0 ;i < times ; i ++){        s3.append("a");    }    long d = System.currentTimeMillis();    System.out.print((b-a) + " | " + (c-b) + " | " + (d-c));}

輸出結果

7289 | 1593 | 5

 

2.比較 String、HashSet、List 中的 contains 方法

其中, String、List 都使用了 indexOf 方法,本質是遍曆,時間效率為 O(n)。而 HashSet 使用了計算 hash值的方式,時間效率為 O(1) 層級。

 

3.String 中為什麼需要 hashCode 方法?

從String 源碼可以看到其底層實現是 char[],即本質是字元數組。包括索引及大部分功能實現都是使用數組。

public final class String implements xxx  {        private final char value[];    /** Cache the hash code for the string */    private int hash; // Default to 0    public String() {        this.value = "".value;    }    public String(String original) {        this.value = original.value;        this.hash = original.hash;    }

為什麼還需要 hash 值呢?原因是 String 可以作為 HashSet、HashMap 容器的 key,因此需要擷取 key的哈系值。

 

Java 中字串與 []byte 位元組數組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.