【问题标题】:Array list class method that removes an element and returns a new list删除元素并返回新列表的数组列表类方法
【发布时间】:2020-04-02 17:29:50
【问题描述】:

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

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

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 是

谢谢!

【问题讨论】:

  • 您是说array_list 是一个对象数组(Object[])而不是ArrayList?你能把它变成一个 ArrayList 吗?

标签: java arraylist data-structures


【解决方案1】:

首先,您的 cannot invoke (method) on array type Object[] 错误意味着您的 array_list 变量实际上是 Objects 的数组,正如 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 类型。

【讨论】:

    【解决方案2】:

    请注意,只有在 equals() 和 == 与 E 对象相同时,重复才有效。

    【讨论】:

    猜你喜欢
    • 2021-07-10
    • 2015-07-20
    • 2016-06-27
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    相关资源
    最近更新 更多