java中indexofsublist方法
时间: 2024-05-12 15:09:57 浏览: 16
在Java中,`indexOfSubList()`方法是`Collections`类中的一个方法,用于查找一个列表中是否包含另一个列表,并返回第一次出现的位置索引。该方法的语法如下:
```java
public static int indexOfSubList(List<?> source, List<?> target)
```
其中,`source`是要搜索的列表,`target`是要查找的子列表。该方法返回子列表在源列表中第一次出现的位置索引,如果找不到则返回-1。
以下是一个示例代码:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> source = new ArrayList<>();
source.add(1);
source.add(2);
source.add(3);
source.add(4);
source.add(5);
List<Integer> target = new ArrayList<>();
target.add(3);
target.add(4);
int index = Collections.indexOfSubList(source, target);
System.out.println("Index of sublist: " + index); // 输出:2
}
}
```
上述代码中,我们创建了一个源列表`source`和一个目标子列表`target`,然后使用`Collections.indexOfSubList()`方法查找目标子列表在源列表中的位置索引,并将结果打印出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)