问题:方法传参List,并对变量赋值,但是在主方法使用List时,没有赋值成功?
原因:1、是否是方法内的局部变量;2、方法是否已经结束,如果结束,JVM回收结束方法内的局部变量;
解决方案:1、使用addAll();2、使用add();3、使用方法的返回值;
测试代码:
package com.zc.es.util; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @description * @Author zc * @Datetime 2022/7/2 11:35 */ public class TestUtil { public static void main(String[] args) { // 【错误】result集合为空 List<Integer> result1 = new ArrayList<>(); list1(result1); System.out.println("result1.hashCode= "+result1.hashCode()); System.out.println("result1= "+result1); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // 【错误】result集合为空 // 【正确】result集合有值 List<Integer> result2 = new ArrayList<>(); list2(result2); System.out.println("result2.hashCode= "+result2.hashCode()); System.out.println("result2= "+result2); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // 【正确】result集合有值 // 【正确】result集合有值 List<Integer> result3 = new ArrayList<>(); list3(result3); System.out.println("result3.hashCode= "+result3.hashCode()); System.out.println("result3= "+result3); result3.remove(1); System.out.println("移除一个元素result3= "+result3); System.out.println("result3.hashCode= "+result3.hashCode()); System.out.println("result3= "+result3); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // 【正确】result集合有值 // 【正确】result集合有值 List<Integer> result4 = list4(); System.out.println("result4.hashCode= "+result4.hashCode()); System.out.println("result4= "+result4); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // 【正确】result集合有值 } /** */ private static void list1(List<Integer> result){ List<Integer> list = Arrays.asList(1,2,3); result = list; System.out.println("list.hashCode= "+list.hashCode()); } private static void list2(List<Integer> result){ List<Integer> list = Arrays.asList(1,2); result.addAll(list); System.out.println("list.hashCode= "+list.hashCode()); } private static void list3(List<Integer> result){ List<Integer> list = Arrays.asList(1,2,3); list.forEach(x-> result.add(x)); System.out.println("list.hashCode= "+list.hashCode()); } private static List<Integer> list4(){ List<Integer> list = Arrays.asList(1,2,3,4); System.out.println("list.hashCode= "+list.hashCode()); return list; } }
输入结果:
list.hashCode= 30817 result1.hashCode= 1 result1= [] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> list.hashCode= 994 result2.hashCode= 994 result2= [1, 2] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> list.hashCode= 30817 result3.hashCode= 30817 result3= [1, 2, 3] 移除一个元素result3= [1, 3] result3.hashCode= 995 result3= [1, 3] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> list.hashCode= 955331 result4.hashCode= 955331 result4= [1, 2, 3, 4] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Process finished with exit code 0
原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/270993.html