如何使用Java相互链接objecst

时间:2019-03-04 08:47:49

标签: java data-structures linked-list

我有下面的类,并且有多个对象。我需要使用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对象?

2 个答案:

答案 0 :(得分:1)

如果要单个链接列表:

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());
    }
}

在此示例中,“ next”是测试对象的reference。您可以通过构造函数或setter方法为引用分配值。

  

对象是类实例或数组。

     

引用值(通常只是引用)是指向这些值的指针   对象,以及一个特殊的null引用,该引用不引用任何对象。

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

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

答案 1 :(得分:1)

“链接”在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的“链接”,并且可以调用其方法。