Collections.indexOfSubList用于查找子列表在主列表中首次出现的起始索引,基于equals方法进行元素比较,要求顺序完全一致,未找到返回-1,空子列表视为存在于索引0处。
在Java中,Collections.indexOfSubList 是一个实用的工具方法,用于查找一个列表(List)中首次出现某个子列表的位置。它属于 java.util.Collections 工具类,适用于需要在主列表中定位连续子序列的场景。
Collections.indexOfSubList(List source, List target) 接收两个参数:
方法返回第一个匹配项的起始索引,若未找到则返回 -1。
示例代码:ListmainList = 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() 方法进行比较,因此:
返回 -1Listnumbers = Arrays.asList(1, 2, 3, 2, 3, 4); List pattern = Arrays.asList(2, 3); int pos = Collections.indexOfSubList(numbers, pattern); System.out.println(pos); // 输出 1,表示从索引1开始匹配
除了 indexOfSubList 查找首次出现位置,还可以使用 Collections.lastIndexOfSubList 查找最后一次出现的位置。
这在处理重复模式时特别有用,比如日志分析或文本片段匹配。
int lastPos = Collections.lastIndexOfSubList(numbers, pattern); System.out.println(lastPos); // 输出 3
基本上就这些。只要注意数据顺序和对象比较逻辑,indexOfSubList 就能高效完成子集合定位任务,不复杂但容易忽略细节。