我觉得你绕进去了,不用想那么多,运行到哪值是什么都清清楚楚的,为什么要去分析StringBuffer?难道下一次换成StringBuilder就不一样了?难道再下次用反射改字符串就不一样了?
- class T4 {
- public static void main(String[] args) {
- String s1 = new String("hello");
- String s2 = new String("java");
- show(s1, s2);
- System.out.println("=================");
- System.out.println(s1);
- System.out.println(s2);
- }
- public static void show(String s1, String s2) {
- try {
- append(s1, s2);
- System.out.println("S1---" + s1);
- s1 = s2;
- System.out.println("S2---" + s2);
- append(s2, s1);
- System.out.println("S2---" + s2);
- System.out.println("S1---" + s1);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- private static void append(String s1, String s2)
- throws NoSuchFieldException, IllegalAccessException {
- Field value = String.class.getDeclaredField("value");
- value.setAccessible(true);
- char[] v1 = (char[]) value.get(s1);
- char[] v2 = (char[]) value.get(s2);
- char[] v12 = new char[v1.length + v2.length];
- System.arraycopy(v1, 0, v12, 0, v1.length);
- System.arraycopy(v2, 0, v12, v1.length, v2.length);
- value.set(s1, v12);
- }
- }
复制代码
有什么变了吗?
所以有时候不要去看那些细节,那些跟问题没有多少关系,不要自己吓唬自己 |