我实现了ArrayList
这里
public class JsonList<T> extends ArrayList<T>{
//extended functions
}
创建ArrayList时,可以做一些事情List<?> arrayList = new ArrayList<>(alreadyCreatedList);
我希望能够使用我的 JsonList 来做到这一点。但目前,JsonList 只有默认的构造函数 JsonList<>()。我尝试像这样复制 ArrayList 构造函数
public JsonList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// defend against c.toArray (incorrectly) not returning Object[]
// (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
当创建 JsonList 实例时,我这样做
JsonList<?> jsonList = new JsonList<>(alreadyCreatedList);
但是,元素不会保存。它返回 empty array
。另外,我无法再创建空实例JsonList<?> jsonList = new JsonList<>();
解决方案: 我不知道为什么我没有想到这一点,但对于那些在这里的人来说它是
public JsonList(Collection<? extends E> c) {
super(c); // <-- invoke the appropriate super constructor
}
super(c) 就是您所需要的。
最佳答案
制作第一行 super(c);
如果没有的话,编译器将插入 super()
它不会调用您想要的(使用 Collection<? extends E> c
)。
public JsonList(Collection<? extends E> c) {
super(c); // <-- invoke the appropriate super constructor
elementData = c.toArray();
// ...
}
关于java - 扩展 ArrayList 并使用/创建类似的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48533296/