The only usage of
DirectoryStream that I have seen uses the type
Path as its type parameter,
DirectoryStream<Path> which comes from
Additionally, I don't understand why it allows for any type because of the following statement in the documentation:
If hasNext method returns true, and is followed by a call to the next method, it is guaranteed that the next method will not throw an exception due to an I/O error, or because the stream has been closed.
This must mean it checks whether the
Path is accessible beforehand and therefore cannot be a generic type.
java.nio.file.DirectoryStreamuse unbounded generics?
The only usage of
DirectoryStreamthat I have seen uses the type
Pathas its type parameter,
DirectoryStream<Path>which comes from
If you look at
SecureDirectoryStream, that interface extends
DirectoryStream with an unbounded generic. However, the only concrete implementation of
SecureDirectoryStream is also parameterized with
So, the most plausible explanations are:
File, but it was abandoned ... too late to get rid of the parameter entirely.
Either way, the parameter is a harmless anomaly, at the moment.
This must mean it checks whether the Path is accessible beforehand and therefore cannot be a generic type.
The parameter is presumably unbounded because there is no suitable common super-interface for
File. The fact that it can't really be any type is ... unfortunate, but by no means unique. There are other cases where there are implied type requirements are not expressed in the static typing. For example:
ObjectOutputStream.writeObject(Object) method fails if the object doesn't implement
Arrays.sort(Object) method fails if the array elements don't all implement
And I expect there are other examples where some parameterizations of a generic class make little sense.
'This must mean it checks whether the Path is accessible beforehand.' Yes it does.
hasNext() actually fetches the element and returns
false if that fetched element is
So when you call
next() just after
hasNext(), it does not put any extra efforts but just returns that fetched( fetched from
The system is buffering the next element. This from the Javadocs:
Due to read-ahead, the Iterator may return one or more elements after the directory stream has been closed. Once these buffered elements have been read, then subsequent calls to the hasNext method returns false, and subsequent calls to the next method will throw NoSuchElementException.