当contains返回true时如何在列表中查找元素的索引位置


75

我有一个ListHashMap所以我要List.contains找出列表中是否包含指定的HashMap。如果确实如此,我想从列表中获取该元素,那么如何找到该元素所在位置的索引位置?

    List benefit = new ArrayList();
    HashMap map = new HashMap();
    map.put("one", "1");
    benefit.add(map);
    HashMap map4 = new HashMap();
    map4.put("one", "1");

    System.out.println("size: " + benefit.size());
    System.out.println("does it contain orig: " + benefit.contains(map));
    System.out.println("does it contain new: " + benefit.contains(map4));

    if (benefit.contains(map4))
        //how to get index position where map4 was found in benefit list?

Answers:


146
benefit.indexOf(map4)

如果找不到项目,则返回索引或-1。

强烈建议将地图包装在某些对象中,并尽可能使用泛型。


只需稍作注释,在瓶颈代码中,建议仅运行一次列表搜索:int pos = list.indexOf(item); if (pos >= 0) { /* do it */ }
戴维·霍瓦斯


15

这是一个例子:

List<String> names;
names.add("toto");
names.add("Lala");
names.add("papa");
int index = names.indexOf("papa"); // index = 2



1

int indexOf(Object o) 此方法返回指定元素首次出现在此列表中的索引,如果此列表不包含此元素,则返回-1。


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.