java中的意外输出
我已经写了一个代码-java中的意外输出,java,Java,我已经写了一个代码- // Node Class class aNode { // Node Contents int NodeInt; char NodeChar; // constructor aNode() { } aNode(int x, char y) { NodeInt = x; NodeChar = y; } } class MainClass { static aNo
// Node Class
class aNode {
// Node Contents
int NodeInt;
char NodeChar;
// constructor
aNode() {
}
aNode(int x, char y) {
NodeInt = x;
NodeChar = y;
}
}
class MainClass {
static aNode node = new aNode();
public static void main(String[] args) {
node = null;
function(node);
if (node == null) {
System.out.println("Node is null");
}
}
static void function(aNode x) {
if (x == null) {
System.out.println("Node is null");
}
x = new aNode(5, 'c');
System.out.println(x.NodeInt);
System.out.println(x.NodeChar);
}
}
我预计产出为-
Node is null
5
c
Node is null
5
c
Node is null
但当程序返回main时,node的值再次设置为null。所以我得到的输出是-
Node is null
5
c
Node is null
5
c
Node is null
请帮助我修改代码以获得所需的输出。任何帮助都将不胜感激 您正在传递一个静态对象,但在方法函数()中,您没有更改object节点的值。仅更改其他对象的值。因此,在main中,节点的值仅为null。一般来说,这是因为Java将阳极对象的引用副本传递给您的方法。更改此引用不会更改原始引用。您应该知道,
阳极节点
和阳极x
是对不同对象的引用。它是Java特性之一—仅通过值传递。意思是当你打电话的时候
function(node);
您没有将节点
引用传递给方法函数(…)
,而是创建了对同一对象的新引用。但这是一致的
x = new aNode(5,'c');
您正在将引用x
设置为新对象。因此,node
仍然引用null和x
引用new阳极
要获取有关在Java中传递参数的更多信息
引用数据类型参数(如对象)也传递到
方法按值排序。这意味着当方法返回时
传入的引用仍然引用与以前相同的对象。
但是,可以在中更改对象字段的值
方法,如果它们具有适当的访问级别
在函数()中,x只是一个局部变量。在Java中重新分配引用时,修改的是引用本身的内容,而不是引用对象的内容。在Java中无法传递对象的地址。如果需要这样的行为,可以尝试使用像Wrapper这样的泛型类,在Java中不可能实现真正的按引用传递。Java按值传递所有内容,包括引用。
。
因此,您必须稍微更改代码以获得所需的输出:
class aNode{
//Node Contents
int NodeInt;
char NodeChar;
//constructor
aNode(){
}
aNode(int x, char y){
NodeInt = x;
NodeChar = y;
}
}
class JavaApplication8{
static aNode node = new aNode();
public static void main(String[] args){
node = null;
node=function(node);
if(node == null){
System.out.println("Node is null");
}
}
static aNode function(aNode x){
if(x == null)
{
System.out.println("Node is null");
}
x = new aNode(5,'c');
System.out.println(x.NodeInt);
System.out.println(x.NodeChar);
return x;
}
}
输出:
Node is null
5
c
看看这有什么帮助!!现在我在函数中使用了一个return语句,它覆盖了main中的值,并且是固定的。谢谢你的帮助:)