我需要编写一个方法作为数组列表类的一部分,该方法接受一个元素作为参数
该方法会删除该元素的所有实例,然后返回仅包含该元素的新列表
my_model = MyModel.limit(1000).offset(1000)
这是我到目前为止所拥有的...两件事:
然后2.我一直无法对array_list是数组类型的Object []调用(方法)
谢谢!
答案 0 :(得分:0)
首先,您的cannot invoke (method) on array type Object[]
错误意味着您的array_list
变量实际上是Object
的数组,正如乔尼(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
类型。
答案 1 :(得分:0)
请注意,只有equals()
对象的==
和E
相同时,重复项才是好的。