Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing “aa” with “b” in the string “aaa” will result in “ba” rather than “ab”.
替换从字符串的开头一直进行到结尾,匹配成功就替换,然后接下去。
例如:原字符串:aaa ,将 aa 替换为 b ,则结果是 ba 而不是 ab ,因为是从前往后。
replace 两个重载方法
1
public String replace(char oldChar, char newChar)/* 替换一个字符 */
1
public String replace(CharSequence target, CharSequence replacement)/* 替换一个串 */
replaceAll
1
public String replaceAll(String regex, String replacement)/* 前面正则表达式,匹配成功替换为后面字符串 */
举例🌰:原串 s 里的 * 替换为 A 两种写法:
s.replaceAll("\\*", "A") 只能接正则表达式匹配出来替换。
s.replace("*", "A")
replaceFirst 只替换第一个匹配字符串
1
public String replaceFirst(String regex, String replacement)
2. 「Integer不能用 == 判断?」
1 2 3
Integer orderStatus1 = new Integer(1); Integer orderStatus2 = new Integer(1); System.out.println(orderStatus1 == orderStatus2);
结果会返回 false
不是说 Integer 有缓存吗,范围是 -128 ~ 127
1 2 3
publicInteger(int value){ this.value = value; }
有参构造并没有用到缓存
1 2 3 4 5
publicstatic Integer valueOf(int i){ if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; returnnew Integer(i); }
要用到缓存,就应该使用 valueOf 方法
1 2 3
String orderStatus1 = new String("1"); String orderStatus2 = new String("1"); System.out.println(Integer.valueOf(orderStatus1) == Integer.valueOf(orderStatus2));
The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal(“0.1”) creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.
When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.
public BigDecimal(double val) 这种构造方法生成的结果不可预测(unpredictable)