为什么输出结果是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); } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 求解 yolo算法问题
- ¥15 虚拟机打包apk出现错误
- ¥30 最小化遗憾贪心算法上界
- ¥15 用visual studi code完成html页面
- ¥15 聚类分析或者python进行数据分析
- ¥15 逻辑谓词和消解原理的运用
- ¥15 三菱伺服电机按启动按钮有使能但不动作
- ¥15 js,页面2返回页面1时定位进入的设备
- ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
- ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。