← 中文资源

简体中文版本

indexOfSubList 定位嵌套序列

Collections.indexOfSubList 在大列表里匹配连续元素段并返回起始下标:indexOf 只找单元素,lastIndexOfSubList 从尾部反查,找不到或目标比源长时返回 -1,空目标按正式规范匹配下标 0。

阅读英文原文

实现说明

全部逻辑都在类 PatternWindow和函数 main中。

使用要点

  • 直接运行文件,输出会带上标签,比如 indexOf read:、read,write window:、last read,write:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「indexOfSubList 定位嵌套序列」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 indexOf read:、read,write window:、last read,write: 这类标签。

代码示例

import java.util.Collections;
import java.util.List;

public class PatternWindow {

    public static void main(String[] args) {
        List<String> events = List.of(
                "boot", "login", "read", "write", "read", "write", "logout");

        // indexOf 只找单个元素;indexOfSubList 匹配连续的元素序列
        System.out.println("indexOf read: " + events.indexOf("read"));
        System.out.println("read,write window: "
                + Collections.indexOfSubList(events, List.of("read", "write")));

        // 从后往前找最后一次出现的起始下标
        System.out.println("last read,write: "
                + Collections.lastIndexOfSubList(events, List.of("read", "write")));

        // 空目标按正式规范匹配下标 0;找不到或目标比源长都返回 -1
        System.out.println("empty pattern: "
                + Collections.indexOfSubList(events, List.of()));
        System.out.println("missing run: "
                + Collections.indexOfSubList(events, List.of("write", "read", "write", "read")));
    }
}