为什么我添加到不同列表的所有节点最终都在一个列表中?

Why are all of the nodes that I add to different lists ends up in one list?

我有两个 class,RectNode 和 RectList。任务是创建一个矩形列表(另一个 class 称为 RectangleA)。当我使用测试器时,似乎所有节点都被添加到所有列表中,即使我创建了不同的列表。例如,测试人员创建了两个列表:rL1rL2。然后它向第一个列表添加一个矩形,向第二个列表添加一个。问题是,当我 运行 测试仪并​​使用我创建的 toString() 方法打印两个列表时,它显示两个矩形都在两个列表中。谁能帮我找到问题所在? 当运行宁测试时:

rL1:列表有 2 个矩形。

  1. 宽=5 高=7 点SW=(0,0)
  2. 宽=3 高=8 点SW=(0,0)

rL2:列表有 2 个矩形。

  1. 宽=5 高=7 点SW=(0,0)
  2. 宽=3 高=8 点SW=(0,0)

classes:

public class RectList
{
    private static RectNode _head;
    public RectList(){
        _head = null;
    }
    public static void addRect(RectangleA r){
        if(empty()){
            _head = new RectNode(r);
        }else{
            boolean isThereRectangle = false;
            RectNode ptr = _head;
            while(ptr.getNext() != null){
                if(ptr.getRect().equals(r)){
                    isThereRectangle = true;
                }
                ptr = ptr.getNext();
            }
            if(ptr.getRect().equals(r)){
                isThereRectangle = true;
            }
            if(isThereRectangle == false){
                ptr.setNext(new RectNode(r));
            }
        }
    }
    public String toString(){
        String list = "";
        int counter = 0;
        if(!empty()){
            RectNode ptr = _head;
            while(ptr != null){
                counter++;
                list += (counter + ". " + ptr.getRect().toString() + "\r\n");
                ptr = ptr.getNext();
            }
        }
        return ("The list has " + counter + " rectangles." + "\r\n" + list);
        
    }
}
public class RectNode
{
    private RectangleA _rect;
    private RectNode _next;
    public RectNode(RectangleA r){
        _rect = r;
        _next = null;
    }
    public RectNode(RectangleA r, RectNode n) {
        _rect = r;
        _next = n;
    }
    public RectNode(RectNode r){
        _rect = r._rect;
        _next = r._next;
    }
    public RectangleA getRect(){
        return new RectangleA(_rect);
    }
    public RectNode getNext(){
        return _next;
    }
    public void setRect(RectangleA r){
        _rect = new RectangleA(r);
    }
    public void setNext(RectNode next){
        _next = next;
    }
}

public class test
{
    public static void main(String[] args) {
        RectList rL1 = new RectList();
        RectList rL2 = new RectList();
        RectangleA r1 = new RectangleA(5, 7);
        RectangleA r2 = new RectangleA(3, 8);
        rL1.addRect(r1);
        rL2.addRect(r2);
        System.out.println("rL1: " + rL1.toString() +"\nrL2: " + rL2.toString());
    }
}

您的 _head 变量是 RectList class 的 static 属性。 static 个成员在所有出现的 class 中具有相同的值。 所以当你做 rL1.addRect(r1); rL2 时也会得到 r1 作为它的头部。 然后你做 rL2.addrect(r2) 并将 r2 添加到 head 的引用,这是两个对象的相同 head (因为 head 是静态变量)。

您只需删除 static 关键字,它就可以解决问题。