为什么输出结果是hello,而不是hellow,我附了张图片。
17条回答 默认 最新
思想永无止境 2016-11-24 05:33关注1.在一个方法内对一个参数的引用重新赋值对原对象是没有任何影响的。
2.要想对原对象产生影响,你只能对该参数引用指向的对象内部进行修改
如:public static void test(StringBuilder sb){ sb.append("w"); } public static void main(String[] args) { StringBuilder sb = new StringBuilder("hello"); test(sb); System.out.println(sb); }3.String是不可变对象,它没有提供任何可以修改自己的方法。
4.new和双引号创建String的区别在于new会在堆和常量池里都创建一个String,双引号就只在常量池里创建。
5.如果一定要改怎么办?
5.1 换成StringBuffer或StringBuilder
5.2 返回修改后的字符串并接收后重新赋值
就是@avivadepp这位哥们的回答。
5.3 放入Map、List、数组等等对象里。
示例:import java.util.Arrays; import java.util.List; public class Test { String str; public Test(String str) { this.str = str; } public static void test1(String[] ss){ ss[0]=ss[0]+"w"; } public static void test2(List<String> ss){ ss.set(0,ss.get(0)+"w"); } public static void test3(Test ss){ ss.str=ss.str+"w"; } public static void main(String[] args) { String[] s1={"hello"}; test1(s1); System.out.println(s1[0]); List<String> s2=Arrays.asList(new String[]{"hello"}); test2(s2); System.out.println(s2.get(0)); Test s3 = new Test("hello"); test3(s3); System.out.println(s3.str); } }本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报