当包含返回 true 时,如何查找列表中元素的索引位置

我得到了 HashMapList,所以我使用 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?
290050 次浏览

使用 List.indexOf()。当有多个重复时,这将给你 第一匹配。

benefit.indexOf(map4)

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

很强烈建议在一些对象中包装映射,如果可能的话使用泛型。

int indexOf(Object o) 此方法返回此列表中指定元素的第一个匹配项的索引,如果该列表不包含此元素,则返回 -1。

这里有一个例子:

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

可以使用 int indexOf()。如果没有找到匹配,则返回 -1

这应该简单地返回映射的索引,或者如果它不存在,返回 -1。