int 和字符串操作的思考

引言

今天写代码的时候,看到了一些 int 和 stirng 类型数据相加的操作,想到了一些小问题🤔

1
2
3
4
String a = "";
int b = -123;
String strB = Integer.toString(b);
String strC = a + b;

Integer.toString()内部方法

1
2
3
4
5
6
7
8
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);
}

思考为何 ""+ int 能完成为何这种还存在,

想了想,String相加的时候,内部转换应该也是用了一样的方法,众所周知,

字符串相加会自动优化成 StringBuild 操作,

StringBuilder 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Override
public StringBuilder append(int i) {
super.append(i);
return this;
}

====================
点进super进去
====================

public AbstractStringBuilder append(int i) {
if (i == Integer.MIN_VALUE) {
append("-2147483648");
return this;
}
int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
: Integer.stringSize(i);
int spaceNeeded = count + appendedLength;
ensureCapacityInternal(spaceNeeded);
Integer.getChars(i, spaceNeeded, value);
count = spaceNeeded;
return this;
}

果然,和 Integer里的方法基本一个道理,🤣🤣🤣🤣🤣


int 和字符串操作的思考
http://xxpain.github.io/2021/07/23/字符串/
作者
无情小肥羊
发布于
2021年7月23日
许可协议