java - 数组列表类方法,删除元素并返回新列表

标签 java arraylist data-structures

我需要编写一个方法作为数组列表类的一部分,该方法接受元素作为参数

该方法删除该元素的所有实例,然后返回仅包含该元素的新列表

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;
    }
}

这是我到目前为止所拥有的......两件事:

  1. 这行得通吗?

还有 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/

相关文章:

python - 使用Python模块Glom,将不规则嵌套列表提取到扁平字典列表中

java - IntelliJ - 运行程序

java - 使用 not in with join 和 between with HQL

java - Elasticsearch - 映射异常

java - android - java - 带有 ArrayList 的 WeakReferences?

sorting - 将部分散列集副本存储在有序集中的删除安全方法

java - 使用Tomcat服务器缓存数据

java - 添加到对象的 ArrayList 中?

java - Java中整数字符串与字符串的比较

C++ - 错误列表的数据结构