gpt4 book ai didi

java - 我的递归列表的前置功能创建了一个无限列表

转载 作者:行者123 更新时间:2023-12-02 06:25:07 24 4
gpt4 key购买 nike

目前,我正在用 Java 开发一个通用列表。问题:前置方法无法按其应有的方式工作。它不是在索引 0 处添加元素 T,而是创建一个无限递归列表。

public class Vector<T>{

private T value;
private Vector<T> next = null;

public Vector(T value){
this.value = value;
}

public Vector(T value, Vector<T> next){
this.value = value;
this.next = next;
}

public void prepend(T element){
this.next = this;
this.value = element;
}
}



public class Main{
...
Vector<Integer> v1 = new Vector<Integer>(new Integer(1));
v1.prepend(new Integer(0));
...

预期输出:{0,1}实际输出:{0,0,0,0,0,0,0,........ }

最佳答案

您正在做什么:首先,创建一个 Vector,其 value = 1,next = null。 “Prepending” 0,你在这个旁边设置一个无限递归,然后你设置值= 0。如果你查看你的 vector ,你首先得到值= 0。然后你改变到下一个 vector ,仍然是这个。对于该"new" vector ,您输出值 = 0。然后更改为下一个 vector ,仍然是这个。对于该"new" vector ,您输出值 = 0。然后...您就得到了它。

您最可能想做的事情:在前面添加一个整数时,您希望将其复制到下一个并将值设置为新的整数。内容如下:

public class Vector<T>{

[…]
public void prepend(T element){
this.next = new Vector<>(value, next); // a Copy Constructor would also be fine
this.value = element;
}
}

关于java - 我的递归列表的前置功能创建了一个无限列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55793916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com