Collections.indexOfSubList用于查找子列表在源列表中的起始索引,基于equals方法匹配,返回首个完全匹配的索引或-1,空列表视为任意列表的子集。

在Java中,Collections.indexOfSubList 是一个实用方法,用于查找一个子集合(sublist)在源集合中的起始位置。这个方法适用于 List 类型的集合,返回子集合第一次出现的索引,如果未找到则返回 -1。
indexOfSubList 基本用法
该方法属于 java.util.Collections 工具类,定义如下:
public static int indexOfSubList(List source, List target)
其中:
source:原始列表,从中查找子集合target:要查找的子集合
返回值是子集合在源列表中首次完整匹配的起始索引。
立即学习“Java免费学习笔记(深入)”;
示例代码:
Shakker
多功能AI图像生成和编辑平台
103 查看详情
List mainList = Arrays.asList(“a”, “b”, “c”, “d”, “e”);
List subList = Arrays.asList(“c”, “d”);
int index = Collections.indexOfSubList(mainList, subList);
System.out.println(index); // 输出:2
使用注意事项与技巧
该方法基于元素的 equals() 方法进行比较,因此:
确保集合中的对象正确重写了 equals() 方法,尤其是自定义对象时顺序必须完全一致,包括重复元素空集合(empty list)被视为任何列表的子集,其索引为 0
自定义对象示例:
class Person {
String name;
Person(String name) { this.name = name; }
// 必须重写 equals 方法
@Override
public boolean equals(Object o) {
if (!(o instanceof Person)) return false;
return name.equals(((Person)o).name);
}
}
List people = Arrays.asList(new Person(“Alice”), new Person(“Bob”));
List query = Arrays.asList(new Person(“Bob”));
int pos = Collections.indexOfSubList(people, query); // 正确返回 1
常见问题与替代方案
该方法只返回第一个匹配位置。若需查找所有匹配位置,可手动遍历或结合 subList() 实现:
public static List findAllSubListIndices(List source, List target) {
List indices = new ArrayList();
int index = 0;
while (index if (Collections.indexOfSubList(source.subList(index, source.size()), target) != -1) {
indices.add(index);
index += Collections.indexOfSubList(source.subList(index, source.size()), target) + 1;
} else break;
}
return indices;
}
对于非 List 集合(如 Set),indexOfSubList 不适用,因为无序结构无法定义“连续子序列”。
基本上就这些。只要注意类型、顺序和 equals 实现,indexOfSubList 能高效完成子集合定位任务。
以上就是Java里如何用Collections.indexOfSubList查找子集合位置_子集合查找技巧说明的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1102725.html
微信扫一扫
支付宝扫一扫