Java modify the parameters content when mass participation

When the following personal point of view:

Java Chuan Chuan is a reference parameter, and is using the final modification of the parameters. This will not lead to a reference point to another object.

public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    map.put("a", "a");
    
    change1(map);
    System.out.println(map.size());  // 输出结果 1

    change2(map);
    System.out.println(map.size());  // 输出结果 2
}

// 直接将参数指向另一个对象,不会修改原参数
public static void change1(Map map) {
    map = new HashMap<>();
}

// 修改内容,可以修改参数
public static void change2(Map map) {
    map.put("b", "b");
}

In the pass parameters, under the premise of points does not modify the parameters, modify its contents can modify the original parameters.

String type is immutable, when the value is changed, a new object is generated, and the pointer to the new object, it can not modify the parameter values ​​by the above method.

public static void main(String[] args) {
    String str = "a";
    
    change1(str);
    System.out.println(str); // 输出结果 a

    change2(str);
    System.out.println(str); // 输出结果 a

    change3(str);
    System.out.println(str); // 输出结果 ab

}

// 改变值,实际已经指向了新的对象,不会修改原参数
public static void change1(String str) {
    str += "b";
}

// 指向新的对象,不会修改原参数
public static void change2(String str) {
    str = new String("ab");
}

// 通过反射修改值,可以修改原参数
public static void change3(String str) {
    Field valueField = null;
    try {
        valueField = String.class.getDeclaredField("value");
        valueField.setAccessible(true);
        char[] ch = {'a', 'b'};
        valueField.set(str, ch);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

}

 

Published 16 original articles · won praise 3 · Views 4532

Guess you like

Origin blog.csdn.net/qq_29697901/article/details/88730706