数组对象和普通对象初始化 [英] Array Object and Ordinary object Initialization

查看:120
本文介绍了数组对象和普通对象初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个对象 root1,root2,root3 它们出现在 root [] (数组对象)中这是一组对象。

I have 3 objects root1,root2,root3 where they are present in root[] (Array Object) which is a collection of objects.

我使用 root初始化了 Node 类0] 。所以
我可以通过 root [0] .data 访问 Node 类的值但是我我希望 root1.data 也应该访问同一个类,因为 root [0] = root1 ,但我无法访问访问该值。

I have initialized the Node class using root[0]. So I am able to access the value of Node class through root[0].data but I am expecting root1.datashould also access the same class because root[0]=root1, but I am not able to access the value.

为了理解我的逻辑,我还需要做些什么吗?
我有以下程序:

Is there anything I need to do in order to work my logic? I have the following program:

class a
{
static Node root1,root2,root3;
public static void main(String args[])
{
Node root[]={root1,root2,root3};
for(int i=0;i<root.length;i++)
    root[i]=new Node(value,null);
    System.out.println(root[i].data);//It is printing Correctly
    System.out.println(root1.data);//It is printing null value

}
public static class Node
{
 int value;
 Node next;
 Node(int value,Node next)
    {
        this.value=value;
        this.next=next;
    }
}
}


推荐答案


我有3个对象root1,root2,root3

I have 3 objects root1,root2,root3

不,你没有。你有三个变量,,它们都是空的。

No you don't. You have three variables, and they are all null.


它们出现在 root []

root [] 初始化时除了三个空值。

Nothing is present in root[] except three nulls when you initialize it.


我初始化了节点类使用 root [0]

您已经实例化 节点类,并将引用存储到 root [0]

You have instantiated the Node class, and stored the reference into root[0].

// It is printing null value.

使用此代码,它应该抛出 NullPointerException

With this code it should be throwing NullPointerException.

root[0]=root1

不,不是。你在循环中覆盖它,无论如何当你进行(无意义的)数组初始化时, root1 为null,因为你没有初始化它。

No it doesn't. You overwrote it in your loop, and in any case when you did the (pointless) array initialization, root1 was null, as you didn't initialize it.

这篇关于数组对象和普通对象初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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