String的源碼以下:數組
public final class String implements Serializable, Comparable<String>, CharSequence{ priviate final char value[]; private int hash; ... }app
String自己是一個名爲value的char數組,String中並無提供任何value的set方法,所以在外部是沒有辦法改變value數組中的內容。ui
value是final類型的,意味着value的指針不可變,可是value中指向的數組是能夠變的。this
當咱們調用Replace方法時,其實是建立了一個新的數組。spa
public String replace(CharSequence target, CharSequence replacement) { return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(this).replaceAll(Matcher.quoteReplacement(replacement.toString())); }
public static String quoteReplacement(String s) { if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1)) return s; StringBuilder sb = new StringBuilder(); for (int i=0; i<s.length(); i++) { char c = s.charAt(i); if (c == '\\' || c == '$') { sb.append('\\'); } sb.append(c); } return sb.toString(); }
能夠使用反射機制來改變value中數組的內容。指針
public static void testReflection() throws Exception{ String s = "Hello World"; System.out.println("s = " + s); Field valueFieldOfString = String.class.getDeclaredField("value"); valueFieldOfString.setAccessible(true); char[] value = (char[]) valueFieldOfString.get(s); value[5] = '_'; System.out.println("s = " + s); }