gpt4 book ai didi

java - ArrayList 类中的 addAll() 方法不起作用

转载 作者:行者123 更新时间:2023-12-01 16:42:24 24 4
gpt4 key购买 nike

我很难理解为什么 ArrayList 中的 addAll() 方法不起作用。我有我的课:

public class XList<E> extends ArrayList<E> {...

}

使用方法:

public XList<E> union(XList<E> input) {
System.out.println(this);//
System.out.println(input);
this.addAll(input);
return this;
}

System.out.println 指示,给定列表中存在正确的值,但添加后,“this”不会更新,而是未经修改地返回。您能告诉我问题的根源吗?非常感谢任何帮助。

SSCCE:

public class Main {
public static void main(String[] args) {
XList<Integer> list1 = new XList<>(1, 3, 9, 11);
XList<Integer> list2 = XList.of(5, 6, 9);


List<Integer> m1 = list1.union(list2);
System.out.println(m1);

}

}

class XList<E> extends ArrayList<E> {

private List<E> lista;

public XList(E a, E b, E c) {
lista = new ArrayList<>();
lista.add(a);
lista.add(b);
lista.add(c);
}

public XList(E a, E b, E c, E d) {
lista = new ArrayList<>();
lista.add(a);
lista.add(b);
lista.add(c);
lista.add(d);

}

static XList of(Integer a, Integer b, Integer c) {

return new XList(a, b, c);
}

public XList<E> union(XList<E> input) {

System.out.println("this: " + this);
System.out.println("input: " + input);
this.addAll(input);
return this;
}


public String toString() {

return lista.toString();
}

最佳答案

您的问题是,您的 XList 令人困惑地既扩展了 ArrayList,又包含一个列表作为字段。这意味着 XList 基本上是两个单独的列表:它本身是一个列表,并且还包含一个不同的单独列表

如果我是你,我会删除“extends ArrayList”并替换

this.addAll(input);

this.lista.addAll(input.lista);

关于java - ArrayList <E> 类中的 addAll() 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60841329/

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