关于String类中replace方法的源代码的疑惑

staticabc 2014-08-04 11:58:42
看了String类的源代码,其中对public String replace(char oldChar, char newChar);这个方法的实现有些疑惑,具体代码是
    public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = count;
int i = -1;
char[] val = value; /* avoid getfield opcode */
int off = offset; /* avoid getfield opcode */

while (++i < len) {
if (val[off + i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0 ; j < i ; j++) {
buf[j] = val[off+j];
}
while (i < len) {
char c = val[off + i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(0, len, buf);
}
}
return this;
}

为什么要先找到第一个可以替换的位置?直接使用循环进行替换不行吗,我写的话应该是这样的:
    public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = count;
int i = 0;
char[] val = value; /* avoid getfield opcode */
int off = offset; /* avoid getfield opcode */
char buf[] = new char[len];

while (i < len) {
char c = val[off + i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(0, len, buf);
}
return this;
}

对于jdk中的源码不理解,求解释!
...全文
691 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_37948262 2017-03-17
  • 打赏
  • 举报
回复
如何编写replace方法呢
Scorpio丶君澜 2016-11-16
  • 打赏
  • 举报
回复
节省内存,少创建很多对象
lw_China 2014-08-05
  • 打赏
  • 举报
回复
就一个目的: 为了快
vnvlyp 2014-08-05
  • 打赏
  • 举报
回复
目测是为了避免创建重复的字符串对象,你那样就算字符串里不包含要replace的字符,还是会创建一个新字符串,这有违String类的设计原则,尽量避免创建两个内容相同的字符串。
猿敲月下码 2014-08-05
  • 打赏
  • 举报
回复
关键是理解那段注释:/* avoid getfield opcode */ 参考:avoid getfield opcode
staticabc 2014-08-05
  • 打赏
  • 举报
回复
引用 4 楼 zy353003874 的回复:
其实没得必要去纠结,每个人的想法不一样 你仔细想想代码就知道了 如果原始字符串是a,现在想要把a替换成为b 即调用replace('a','b')方法,你在看看你的代码是否有不妥之处呢?
没看出来有什么不妥的地方,可以指出来吗
zy_think123 2014-08-04
  • 打赏
  • 举报
回复
其实没得必要去纠结,每个人的想法不一样 你仔细想想代码就知道了 如果原始字符串是a,现在想要把a替换成为b 即调用replace('a','b')方法,你在看看你的代码是否有不妥之处呢?
sunbo624 2014-08-04
  • 打赏
  • 举报
回复
因为有可能char数组中没有oldChar 这样就没必要循环了
staticabc 2014-08-04
  • 打赏
  • 举报
回复
论坛没人吗。。。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧