Java String

String 类是final类,不可以继承。String类实现了CharSequence接口,我们看一下CharSequence的部分代码

public interface CharSequence
{
    //the number of char in this sequence
    int length();
    
    // return the char value at the specified index
    char charAt(int index);
    
    // return a new CharSequence that is a subsequence of this sequence.
    CharSequence subSequence(int start, int end);
    
    //a string consisting of exactly this sequence of characters
    public String toString();
}


我们来看一下String的部分源码,成员变量只有两个:final的char类型数组,int类型的hashcode

public final class String{
    
    // used for character storage
    private final char value[]; 
    
    // cache the hash code for the string
    private int hash; 
}


说到String,应该提一下线程池的概念。每当我们创建一个字符串对象时,首先就会检查字符串池中是否存在面值相等的字符串,如果有,则不再创建,直接放回字符串池中对该对象的引用,若没有则创建然后放入到字符串池中并且返回新建对象的引用。这个机制是非常有用的,因为可以提高效率,减少了内存空间的占用。所以在使用字符串的过程中,推荐使用直接赋值(即String s=”lhw”),除非有必要才会新建一个String对象(即String s = new String(”lhw”))。看如下的代码

public class Test {
    public static void main(String[] args) {
        String one = "lhw";
        String two = "l"+"h"+"w";
        String three= "lhw";
        String four = new String("lhw");
        System.out.println(one==two);
        System.out.println(one==three);
        System.out.println(one==four);
    }
}
输出:
true
true
false

有没有不理解的地方?其实这里有一个JVM 的把戏,在 JVM 眼里,这个String two = "l"+"h"+"w",其实就是String three= "lhw"。
我们来看几个String的方法。
第一部分是构造函数:

public String() {
        this.value = "".value;
    }

public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }

public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }
这里如果不理解,我们看一下Arrays.copyOf的源码:
    public static char[] copyOf(char[] original, int newLength) {
        char[] copy = new char[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
我们看一下length()方法,明显就是直接返回数组的length属性了。

 public int length() {
        return value.length;
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值