当前位置: 动力学知识库 > 问答 > 编程问答 >

Why does java.nio.file.DirectoryStream use unbounded generics?

问题描述:

The only usage of DirectoryStream that I have seen uses the type Path as its type parameter, DirectoryStream<Path> which comes from Files.newDirectoryStream(Path).

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.

网友答案:

Why does java.nio.file.DirectoryStream use unbounded generics?

The only usage of DirectoryStream that I have seen uses the type Path as its type parameter, DirectoryStream<Path> which comes from Files.newDirectoryStream(Path).

If you look at SecureDirectoryStream, that interface extends DirectoryStream with an unbounded generic. However, the only concrete implementation of SecureDirectoryStream is also parameterized with Path.

So, the most plausible explanations are:

  • the parameterization is to enable possible future enhancement, or
  • there was originally an intention to provide directory streams of 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 Path and 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:

  • The ObjectOutputStream.writeObject(Object) method fails if the object doesn't implement Serializable.

  • The Arrays.sort(Object[]) method fails if the array elements don't all implement Comparable.

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 null else true.

So when you call next() just after hasNext(), it does not put any extra efforts but just returns that fetched( fetched from hasNext()) element.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: