String类valueOf(int i)方法的实现

博主发布

Java 库 String 类的 valueOf 方法大致可以分为三种:

  • String.valueOf(Object)
  • String.valueOf(char[])
  • String.valueOf(基本数据类型)


String.valueOf(int i)源码:

public static String valueOf(int i) {
        return Integer.toString(i);
}


Integer.toString(int i)源码:

public static String toString(int i) {
        if (i == Integer.MIN_VALUE)
            return "-2147483648";
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
        char[] buf = new char[size];
        getChars(i, size, buf);
        return new String(buf, true);
}


Integer.getChars(int i, int index, char[] buf)的源码:

static void getChars(int i, int index, char[] buf) {
        int q, r;
        int charPos = index;
        char sign = 0;

        if (i < 0) {
            sign = '-';
            i = -i;
        }

        // Generate two digits per iteration
        while (i >= 65536) {
            q = i / 100;
        // really: r = i - (q * 100);
            r = i - ((q << 6) + (q << 5) + (q << 2));
            i = q;
            buf [--charPos] = DigitOnes[r];
            buf [--charPos] = DigitTens[r];
        }

        // Fall thru to fast mode for smaller numbers
        // assert(i <= 65536, i);
        for (;;) {
            q = (i * 52429) >>> (16+3);
            r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
            buf [--charPos] = digits [r];
            i = q;
            if (i == 0) break;
        }
        if (sign != 0) {
            buf [--charPos] = sign;
        }
    }

其他方式实现MyString1 valueOf(int i)

public static MyString1 valueOf(int i) {
        int n;
        char[] temp;
        int count;

        if (i <= Character.MAX_VALUE)
            return new MyString1(Character.toChars(i));
        else {
            n = i % Character.MAX_VALUE;
            count = i / Character.MAX_VALUE;
            temp = new char[count + 1];
            temp[0] = (char) n;
            for (int j = 1; j <= count; j++)
                temp[j] = Character.MAX_VALUE;
            return new MyString1(temp);
        }
    }
分类: Java

0 条评论

发表评论

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用*标注