Java 从集合中删除元素

Java 从集合中删除元素,java,collections,Java,Collections,我要做的是删除集合中小于指定对象的所有元素。这就是我所拥有的: static void removeAllLessThan(Collection c, Object x) { for(Object a : c) if(a.compareTo(x) < 0) c.remove(a); } static void removeAllLessThan(集合c,对象x){ 对于(对象a:c)如果(a.compareTo(x)

我要做的是删除集合中小于指定对象的所有元素。这就是我所拥有的:

static void removeAllLessThan(Collection c, Object x) {
    for(Object a : c) if(a.compareTo(x) < 0) c.remove(a);
}
static void removeAllLessThan(集合c,对象x){
对于(对象a:c)如果(a.compareTo(x)<0)c.移除(a);
}
这不起作用,因为对象没有compareTo方法。我想知道的是,我应该如何在对象之间进行比较?自然比较器又是什么?谢谢。

使用
收藏
而不是
收藏
,并对收藏中的所有项目实施
可比
。并更改您的方法,如:

static void removeAllLessThan(Collection<Comparable> c, Comparable x) {
    for (Iterator<Comparable> it = c.iterator(); it.hasNext();)
        if (it.next().compareTo(x) < 0)
            it.remove();
}
static void removeAllLessThan(集合c,可比x){
for(Iterator it=c.Iterator();it.hasNext();)
if(it.next().compareTo(x)<0)
it.remove();
}

从使用泛型开始,让调用者声明他想要过滤的对象类型:

static <T> void removeAllLessThan(Collection<T> collection, T t) {...}
注意签名的变化

最后,这是一个非常具体的方法。您需要编写许多几乎相同的方法,如RemoveifCreateThan、removeIfEqualIgnoringCase等。编写一个带有签名的泛型
removeIf
方法

public <T> removeIf(Iterable<? extends T> iterable,
                    Predicate<? super T> predicate){...}

有两种方法可以解决这个问题

首先,您可以使用
Comparable
接口,这意味着该方法应该更改为:

static void removeAllLessThan(Collection<Comparable> c, Comparable x) {
    for(Comparable a : c) if(a.compareTo(x) < 0) c.remove(a);
}

这是和的javadoc。

c
是对象的集合吗?为什么不使用实现
compareTo
而不是
Object
的类呢?因为我希望它适用于任何对象任何随机类型的对象都不能以通用方式进行比较,所以需要不同的逻辑来比较不同类型的对象对象。您自己声明:
这不起作用,因为对象没有compareTo方法
。您需要该方法来获取
集合
static <T> void removeAllLessThan(Iterable<? extends T> iterable,
                                  Comparator<? super T> comparator, T t) {
    for (Iterator<? extends T> it = iterable.iterator(); it.hasNext();) {
        if (comparator.compare(it.next(), t) < 0) {
            it.remove();
        }
    }
}
public <T> removeIf(Iterable<? extends T> iterable,
                    Predicate<? super T> predicate){...}
static void removeAllLessThan(Collection<Comparable> c, Comparable x) {
    for(Comparable a : c) if(a.compareTo(x) < 0) c.remove(a);
}
static void removeAllLessThan(Collection c, Object x, Comparator comp) {
    for(Object a : c) if(comp(a, x) < 0) c.remove(a);
}