1

如何从List<SelectItem>.

public class Sample {
public static void main(String[] args) {
    List<SelectItem> list= new ArrayList<SelectItem>();

    list.add(new SelectItem("abc"));
    list.add(new SelectItem("abcd"));
    list.add(new SelectItem("abcdf"));

    System.out.println("size  :"+list.size());
    System.out.println("List  :"+list);
    list.remove(new SelectItem("abcd"));
    System.out.println("List :"+list.size());


}
}
4

9 回答 9

3

试试这个:

list.remove(1);

1索引在哪里。这将删除此列表中指定位置的元素。

如果要删除基于它的元素,state如下所示:

list.remove(new SelectItem("abcd"));

您必须覆盖该类的.equals().hashCode()方法,SelectItem因为: remove(Object o)在内部使用.equals()来比较元素是否存在于列表中,如果存在,它会删除第一次出现的new SelectItem("abcd")

于 2013-10-09T10:42:03.633 回答
1

用这个:

    SelectItem selectItem = new SelectItem();
    selectItem.setValue("abcd");
    list.remove(selectItem); // Just call the remove method
    // If present, it'll remove it, else, won't do anything
于 2013-10-09T10:43:11.657 回答
1

看来 SelectItem 没有正确实现 equals & hashCode 方法。在这种情况下,您可以遍历列表并删除相应的项目,或者保留对实际选择项目的引用并直接删除该引用。

于 2013-10-09T10:48:19.557 回答
1

似乎SelectItem没有实现equals()。我能看到的唯一选择是遍历每个元素并确定索引,然后使用ArrayList#remove(int index)

于 2013-10-09T10:47:34.763 回答
1

您需要使用Iterator并遍历您的列表。每当找到匹配项(我认为您可以使用getValue()SelectItem 的方法)时,使用迭代器将其删除。

由于您无法更改 的equals()方法SelectItem,因此请像这样使用迭代器

Iterator<SelectItem> itr = list.iterator();
while (itr.hasNext()) {
    SelectItem si = itr.next();
    if (si.getValue().equals("abcd")) {
        itr.remove();
            // You removed what you wanted, you can break here, if you want
    }
}
于 2013-10-09T10:47:57.353 回答
0

为了使您编写的代码能够工作,您需要equals()实现SelectItem.

remove方法的java doc:

removes the element with the lowest index i such
that (o==null ? get(i)==null : o.equals(get(i))) 

请注意提供的条件中的o.equals(get(i))部分。

换句话说 - 执行ArrayList搜索要删除的特定对象。它如何判断某个项目是否是请求的对象?自然地,它使用该equals()方法,并且如果该项目等于您提供的要删除的项目,那么它才会被删除。

请注意:为了与其他收集操作保持一致,您还需要实现该hashCode()方法,使其与该equals()方法一致。

于 2013-10-09T10:43:08.260 回答
0

在 JSF 的上下文中,SelectItem 是 UISelectOne 中的有效选项,当您使用仅接受参数的构造函数时,参数将设置为它的值。

试试这个代码:

public SelectItem getItem(List<SelectItem> items, Object value) {

    for (SelectItem si : items) {
        if (si.getValue().equals(si)) {
            return si;
        }
    }
    return null;

}

并像这样使用:

    list.remove(getItemToRemove(list, "abcd");

这不会在迭代时修改列表,它会返回所需的元素,之后您可以删除它或根据需要使用

干杯

于 2013-10-09T10:47:16.557 回答
0

试试这个代码,

public SelectItem getItemToRemove(List<SelectItem> items, SelectItem item) {
    for (SelectItem si : items) {
        if (si.getValue().equals(item.getValue())) {
            return si;
        }
    }
    return null;
}
于 2013-10-09T10:54:09.953 回答
0

试试这个逻辑,

    for (int i = 0; i < list.size(); i++) {
        if (list.get(i).getValue().toString().equals("abcd")) {
           list.remove(i);
           System.out.println(i); //checking the element number which got removed
        }
    }
于 2020-11-13T06:36:40.917 回答