java 全局变量list_java

allpaths是在findPaths(...)方法中定义的List>,该方法在其范围内调用dfs(...)方法,但是我不明白为什么allpaths不是全局变量,所以为什么要对其进行更新? 那么,调用dfs方法后allpaths List如何更新?

import java.util.*;

class TreeNode {

int val;

TreeNode left;

TreeNode right;

TreeNode(int x) {

val = x;

}

};

class FindAllTreePaths {

public static List> findPaths(TreeNode root, int sum) {

List> allpaths = new ArrayList>();

List cpath = new ArrayList();

dfs(root, sum, cpath, allpaths);

return allpaths;

}

private static void dfs(TreeNode root, int sum, List cpath, List> result){

if(root == null){

return;

}

if(root.val == sum && root.left == null && root.right == null){

cpath.add(root.val);

result.add(cpath);

}

List temp = new ArrayList();

temp.addAll(cpath);

temp.add(root.val);

dfs(root.left, sum-root.val, temp, result);

dfs(root.right, sum-root.val, temp, result);

}

public static void main(String[] args) {

TreeNode root = new TreeNode(12);

root.left = new TreeNode(7);

root.right = new TreeNode(1);

root.left.left = new TreeNode(4);

root.right.left = new TreeNode(10);

root.right.right = new TreeNode(5);

int sum = 18;

List> result = FindAllTreePaths.findPaths(root, sum);

System.out.println("Tree paths with sum " + sum + ": " + result);

}

}

另外,我尝试了以下代码,它是上述方案的缩放版本:

public class Main {

public static void main(String[] args) {

int c = call();

System.out.println(c);

}

public static int call(){

int c=100;

call1(c);

return c;

}

private static void call1(int d){

c=4;

d = 4;

}

}

结果是:c = 100

这表明c对于call1()不是全局的。

编辑:我被尝试以下代码,因为我被告知引用类型变量是通过引用传递的,但这不是正确的:

public class Main {

public static void main(String[] args) {

call();

}

public static void call(){

String c="Jack";

List l = new ArrayList();

l.add(1);

call1(c, l);

System.out.println(c);

System.out.println(l.get(0) + " " + l.get(1));

}

private static void call1(String c, List l){

l.add(2);

c="Jack Ryan";

}

}

但是输出是:Jack 1 2

这意味着String通过值传递,而List通过引用传递。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值