zoukankan      html  css  js  c++  java
  • String源码解析

    1、String源码结构

    public final class String
        implements java.io.Serializable, Comparable<String>, CharSequence {
        /** The value is used for character storage. */
        //用于存储字符的字符数组,值不可更改
        private final char value[];
    
        /** Cache the hash code for the string */
        //该字符的hash code; 默认为0
        private int hash; // Default to 0
    
        ......
    
    }
    

      String类被final修饰,说明该类不能被继承。String类用字符数组存储数据,说明该数组变成了常量,只能被赋值一次。

    2、String类的构造函数

    我们以 String(char value[], int offset, int count)构造函数为例

        //返回一个新的字符串,其中以指定位置的offset的字符开始,长度为count
        public String(char value[], int offset, int count) {
            if (offset < 0) {
                throw new StringIndexOutOfBoundsException(offset);
            }
            if (count <= 0) {
                if (count < 0) {
                    throw new StringIndexOutOfBoundsException(count);
                }
                if (offset <= value.length) {
                    this.value = "".value;
                    return;
                }
            }
            // Note: offset or count might be near -1>>>1.
            if (offset > value.length - count) {
                throw new StringIndexOutOfBoundsException(offset + count);
            }
    	//把一个新指定字符数组(从offset开始,以offset+count结尾)赋值给新的字符串value属性。
            this.value = Arrays.copyOfRange(value, offset, offset+count);
        }
    
        //Arrays.copyOfRange(value, offset, offset+count)方法
        public static char[] copyOfRange(char[] original, int from, int to) {
            int newLength = to - from;
            if (newLength < 0)
                throw new IllegalArgumentException(from + " > " + to);
            char[] copy = new char[newLength];
            System.arraycopy(original, from, copy, 0,
                             Math.min(original.length - from, newLength));
            return copy;
        }
    

      

    System.arraycopy是一个native方法

     public static native void arraycopy(Object src,  int  srcPos,
                                            Object dest, int destPos,
                                            int length);
    

      

      

  • 相关阅读:
    动画02
    动画01
    css过渡
    06强制类型转换
    05强制类型转换
    jetson 安装opencv4.4.0
    cpp中的内置异常
    cpp中std::string和std::wstring 相互转换
    qt creator杂记
    win10 git bash 使用vim 显示 git log
  • 原文地址:https://www.cnblogs.com/linlf03/p/12684622.html
Copyright © 2011-2022 走看看