当前位置: 代码迷 >> java >> 如何使用Java相互链接objecst
  详细解决方案

如何使用Java相互链接objecst

热度:77   发布时间:2023-07-26 14:04:12.0

我有以下课程,并且有多个对象。 我需要使用Java将这些对象相互链接。

class Test{
    int value = 0;

    public Test(int value){
        this.value = value;
    }

    public static void main(String[] arg){
        //creating three objects
        Test test1 = new Test(10);
        Test test2 = new Test(60);
        Test test3 = new Test(80);
    }
}

如何将test1,test2,test3对象彼此链接?

如果要单个链表:

public class Test {

    private int value = 0;

    private Test next;

    public Test(int value){
        this(value, null);
    }

    public Test(int value, Test next){
        this.value = value;
        this.next = next;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Test getNext() {
        return next;
    }

    public void setNext(Test next) {
        this.next = next;
    }

    public static void main(String[] arg){
        Test test1 = new Test(10);

        // via constructor
        Test test2 = new Test(60, test1);

        // via setter
        Test test3 = new Test(80);
        test3.setNext(test2);

        System.out.println(test3.getNext().getNext().getValue());
    }
}

在此示例中,“下一个”是对Test对象的 。 您可以通过构造函数或setter方法将值分配给引用。

对象是类实例或数组。

引用值(通常只是引用)是指向这些对象的指针,还有一个特殊的空引用,它不引用任何对象。

注意,test1,test2,test3也是引用。 “ new”运算符创建Test类的新实例,并返回对创建对象的引用。

如果您的目标不是自己创建链表结构,则只需使用或JDK中的任何其他集合即可。

“链接”在Java中称为引用。 如果一个对象需要指向另一个对象,则需要一个字段来保存该引用作为其内部状态的一部分。

该字段应与类具有相同的类型。 您可以通过设置器,构造函数等填充该字段。

class Test{
    int value = 0;
    Test neighbour;

    public Test(int value){
        this.value = value;
    }

    public void setNeighbour(Test neighbour) {
        this.neighbour = neighbour;
    }

    public static void main(String[] arg){
        //creating three objects
        Test test1 = new Test(10);
        Test test2 = new Test(60);
        Test test3 = new Test(80);

        test3.setNeighbour(test2);
    }
}

现在, test3具有到test2的“链接”,并且可以调用其方法。

  相关解决方案