开发者社区> 问答> 正文

通过其他更改数组的方法进行打印时,为什么数组打印方式不同?

应该得到的结果是0,但我不明白为什么?数组通过其他方法传递时发生更改。

public class Tester { public static int function1 (int [] arr) { arr= function2(arr); return arr[0]; } public static int[] function2 (int [] arr) { arr = new int[4]; return arr; } public static void main(String[] args) { int arr[] = {1,2,3,4}; System.out.print(Tester.function1(arr)); } } 我希望从打印出来的答案中得到4。

展开
收起
小六码奴 2019-10-16 19:48:37 9122 0
2 条回答
写回答
取消 提交回答
  • 精于基础,广于工具,熟于业务。

    return arr[0]。这个改成return arr【3】试试

    2019-10-17 08:34:26
    赞同 展开评论 打赏
  • 你正在function2中创建一个全新的数组。这就是为什么默认情况下它在每个索引中存储0的原因。当你返回时,新数组仅是返回。对于每个索引,它将仅打印0。为什么要在函数2中创建新数组?如果必须打印4,则只需仅传递现有数组并打印arr[3]。

    这是代码:-

    public class Tester { public static int function1 (int [] arr) { arr= function2(arr); //return arr[0]; return arr[3]; } public static int[] function2 (int [] arr) { //arr = new int[4]; return arr; } public static void main(String[] args) { int arr[] = {1,2,3,4}; System.out.print(Tester.function1(arr)); } }

    2019-10-16 19:50:08
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载