我需要编写一个方法作为数组列表类的一部分,该方法接受元素作为参数
该方法删除该元素的所有实例,然后返回仅包含该元素的新列表
public List<E> removeSubList(E element) {
ArrayList<E> removedList = new ArrayList<E>();
while(array_list.contains(element)) {
removedList.add(array_list.remove(array_list.indexOf(element)));}
return removedList;
}
}
这是我到目前为止所拥有的......两件事:
- 这行得通吗?
还有 2. 我不断收到无法在数组类型 Object[] 上调用(方法)的消息,其中 array_list 是
谢谢!
最佳答案
首先,您的 cannot invoke (method) on array type Object[]
错误意味着您的 array_list
变量实际上是 Object
的数组s,正如 Joni 的回答。
以下代码是一个静态方法,它采用 ArrayList
的额外参数。这对应于您的 array_list
变量。
public static <E> List<E> removeSublist( E elt, ArrayList<E> aList) {
// first, count the number of occurrences of the element
int numOccurrences = Collections.frequency(aList, elt);
// remove all occurrences of elt from your list
aList.removeIf( currentElt -> currentElt.equals(elt));
// return a list with numOccurrences duplicates of elt
return Collections.nCopies(numOccurrences, elt);
}
您的循环方法也可以工作,但更有效的是立即删除所有出现的情况,然后返回一个包含相应数量的 elt
重复项的列表。如果您要使用循环方法,则需要将 return
语句放在循环外部。
要使此方法成为 ArrayList
的自定义子类的一部分,只需将签名更改回原来的签名即可。但请确保 array_list
实际上是 ArrayList
类型。
关于java - 数组列表类方法,删除元素并返回新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60997546/