File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes indexOfSubList in Collections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "indexOfSubList in Collections" Watch "indexOfSubList in Collections" New topic

indexOfSubList in Collections

sam White
Ranch Hand

Joined: Feb 18, 2011
Posts: 229

I found the logic of indexOfSubList() in Collections is not so correct, as shown below:

1. if source list is not empty and target list is empty, the function returns 0.
2. if source list and target list is empty , the function returns 0.

if 0 means the first element, the function should returns -1 as per the above two points.

Here is my own implementation to address the above issues:

any suggestion is highly appreciated.

Rob Spoor

Joined: Oct 27, 2005
Posts: 20274

An empty list can be found between any two elements of a list, as well as before the first and after the last. This is similar to how there's an empty String between any two characters of any String, as well as before the first and after the last.

Following the above logic, indexOfSubList should return 0 (before the first element) when looking for an empty list. -1 means the empty list cannot be found, and that's certainly not the case.

How To Ask Questions How To Answer Questions
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46362
The empty list is a sublist of every list, the empty set is a subset of every set, and the empty String is a substring of every String. If there are positions, those sub-things can be found at any positions.

Something we forget so often, and get confused about.
I agree. Here's the link:
subject: indexOfSubList in Collections
It's not a secret anymore!