# String相关类

## String

* 1.String是不可变的字符数列，因为源码加了final修饰。
* 2.字符串比较

最好用equals方法（如果不明白，请看面向对象的==与equals）。

```java
package com.itcode.demo4;  

/** 
 * @Auther: 成都码到功成学员 
 * @Description: 
 * String类测试 
 */  
public class TestWrapper3 {  

    public static void main(String[] args) {  
        //  
        String a = "码到功成";  
        String b = "码到" + "功成";// 编译器自动优化拼接变成"码到功成"  
        System.out.println(a==b);// true  
        String c = "码到";  
        String d = "功成";  
        String e = c + d;  
        System.out.println(e==a);//false  
    }  
}
```

## StringBuffer和StringBuilder

概述:是可变的字符数列。StringBuffer和StringBuilder都继承了抽象类AbstractStringBuilder，源码中 ，没有加final修饰。它们的区别是：

* StringBuffer：安全，效率低。
* StringBuilder：不安全，效率高（一般使用这个）。

示例：

```java
package com.itcode.demo4;  

/** 
 * @Auther: 成都码到功成学员 
 * @Description: 
 * StringBuffer类测试 
 */  
public class TestWrapper4 {  

    public static void main(String[] args) {  
        //  
        StringBuffer sb = new StringBuffer("abc123");  
        System.out.println(sb);  
        System.out.println(Integer.toHexString(sb.hashCode()));//打印哈希值  
        sb.setCharAt(2,'S');//把下标2的值替换为S  
        System.out.println(sb);  
        System.out.println(Integer.toHexString(sb.hashCode()));  
    }  
}
```

效果：

![](https://3884904792-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT30K7z1iNbyIaGVh%2F-LxVH-DsB4y0lJ8xCby5%2F-LxVHmek0O8olf1hxW2K%2Fimage.png?alt=media\&token=d61a5812-ce0d-45ac-9b86-21a648dbed16)

看哈希值都是1b6d356。

## 常用方法

StringBuffer和StirngBuilder的方法几乎一模一样。

它们有些方法和String类似，比如： indexOf(String str)、indexOf(String str, int fromIndex)、length()、charAt(int index)、substring(int start, int end)、substring(int start)。

特有方法请看代码示例：

```java
package com.itcode.demo4;  

/** 
 * @Auther: 成都码到功成学员 
 * @Description: 
 * StringBuffer和StringBuilder类测试 
 */  
public class TestWrapper4 {  

    public static void main(String[] args) {  
        //  
        StringBuilder sb = new StringBuilder();  
        // 打印26个字母  
        for (int i=0; i<26;i++){  
            sb.append((char)('a'+i));  
        }  
        System.out.println(sb);  
        System.out.println(sb.reverse());//反转  
        sb.setCharAt(1, '好');// 替换  
        System.out.println(sb);  
        sb.insert(0, "成都").insert(1,"码到功成");// 插入  
        System.out.println(sb);  
        sb.delete(5, 10);// 删除  
        System.out.println(sb);  
    }  
}
```

效果：

![](https://3884904792-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT30K7z1iNbyIaGVh%2F-LxVH-DsB4y0lJ8xCby5%2F-LxVHwwVCInPBFdADEIM%2Fimage.png?alt=media\&token=bcad9910-e146-435c-b2aa-af04aeee6cda)

## 时间内存对比

可变比不可变更不占空间和耗用内存。

示例：

```java
package com.itcode.demo4;  

/** 
 * @Auther: 成都码到功成学员 
 * @Description: 
 * 测试String和StringBuilder做一样的事占用内存和时间比较 
 */  
public class TestWrapper5 {  

    public static void main(String[] args) {  
        // String  
        String s = "";  
        long num1 = Runtime.getRuntime().freeMemory();// 测试内存  
        long time1 = System.currentTimeMillis();// 获取时间毫秒值  
        for(int i=0; i<5000;i++){  
            s += i;//相当于创建10000个对象  
        }  
        long num2 = Runtime.getRuntime().freeMemory();// 测试内存  
        long time2 = System.currentTimeMillis();// 获取时间毫秒值  
        System.out.println("String所占内存："+(num1-num2));  
        System.out.println("String所花时间："+(time2-time1));  
        // String  
        StringBuilder sb = new StringBuilder();  
        long num3 = Runtime.getRuntime().freeMemory();// 测试内存  
        long time3 = System.currentTimeMillis();// 获取时间毫秒值  
        for(int i=0; i<5000;i++){  
            sb.append(i);  
        }  
        long num4 = Runtime.getRuntime().freeMemory();// 测试内存  
        long time4 = System.currentTimeMillis();// 获取时间毫秒值  
        System.out.println("StringBuilder所占内存："+(num3-num4));  
        System.out.println("StringBuilder所花时间："+(time4-time3));  
    }  
}
```

效果：

![](https://3884904792-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT30K7z1iNbyIaGVh%2F-LxVH-DsB4y0lJ8xCby5%2F-LxVI37XiqP71cQG6CL_%2Fimage.png?alt=media\&token=45fbc22b-6c5d-4143-a629-283f8dffe645)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/java/javaji-chu/chang-yong-lei/string-xiang-guan-lei.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
