Java中对数组进行操作的函数处理完后函数不会改变,仍然是原来的函数的原因

    科技2023-09-27  96

    今天运行下面这个函数的时候在函数里面输出的是处理完的数组,跳出后仍然是原来的数组。

    public static void moveZeroes1(int[] nums) { HashMap<Integer,Integer>hashMap=new HashMap<Integer, Integer>(); int t=0; for (int i = 0; i < nums.length; i++) { if(nums[i]!=0){ hashMap.put(t,nums[i]); t++; } } // System.out.println("hashMap:"+hashMap); nums=new int[nums.length]; for (int i=0;i< t;i++){ nums[i]=hashMap.get(i); } // System.out.println(Arrays.toString(nums)); } public static void moveZeroes(int[] nums) { }

    原因是nums=new int[nums.length];这一句,给nums重新赋了一个引用地址,作用效果只是在这个函数里面时,当跳出当前函数的时候,函数对应的引用回到了原先函数对应的位置,索引函数没有发生改变。

    Processed: 0.009, SQL: 8