一, 字符串
1. += 重载符号 与 concat
str1 += str2 : 底层用的 StringBuilder 效率更高, 但是不够灵活, 在某些情况下效率反而较低.
str1 = new StringBuilder().append(str1).append(str2).toString();
concat: 返回一个新的字符串, 在字符串很少时, 效率稍高.
StringBuilder: 使用 append 拼接, 在多段字符串拼接时效率高.
- @org.junit.Test
- public 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 的哈系值.
来源: http://www.bubuko.com/infodetail-2742725.html