关于功能的简单问题 [英] simple question about function

查看:49
本文介绍了关于功能的简单问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class test {
	private Node head;
	
	private class Node{
		int p;
		Node next;
		
		public Node(int p, Node next) {
			this.p = p;
			this.next = next;
		}
	}
	
	public void set() {
		set(head);
	}
	
	private void set(Node p) {
		p = new Node(1, null);
	}
	
	public boolean isEmpty() {
		return head == null;
	}
	
	public static void main(String[] args) {
		test a = new test();
		a.set();
		System.out.println(a.isEmpty());
	}
}





set()函数calss set(head),然后我认为p = head ,和私人集(节点p)



如果要初始化头部,但事实是头部没有初始化,所以我知道为什么



the set() fuction calss set(head), then i think p = head, and the private set(Node p)

if to initialize the head, but the fact is that head is not initialized, so i what to know why

推荐答案

Java按值传递函数参数,而不是按引用传递 - 所以当你将 head 传递给 set function,它复制变量的当前值,并传递该值 - 您对函数中的值所做的任何更改仅影响副本,而不会反映到原始变量中。



为了做你想做的事,你需要从函数中返回新值并设置 head 那个。
Java passes function parameters by value, not by reference - so when you pass head to the set function, it copies the current value of the variable, and passes that value - any changes you make to the value within the function affect only the copy and are not reflected by into the original variable.

In order to do what you want, you would need to return the new value from the function and set head to that.


这篇关于关于功能的简单问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆