"String".trim() == "String".trim();//true
"String".replace('g','G')== "String".replace('g','G');//false
"String".replace('t','t') == "String";//true
以上方法应该返回的都是一个新的String对象 ,而==应该比较的是字符串的对象,==号左右两边返回的都是新的字符串对象,怎么会相等呢?
"String".replace('g','G')== "String".replace('g','G');//false
"String".replace('t','t') == "String";//true
以上方法应该返回的都是一个新的String对象 ,而==应该比较的是字符串的对象,==号左右两边返回的都是新的字符串对象,怎么会相等呢?
最好不要这样用,用equals()
项目中如果很多这样的比较可以考虑重写这个方法
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;
}
读完这个你就会明白了