Salahin Rocky
Salahin Rocky

Reputation: 435

In what sequence Java FileVisitor work

The answer to this question is B and C. I understand why B is one of the answers, but I can't understand why C is also correct.

Can someone explain why is C correct?

enter image description here

Upvotes: -3

Views: 79

Answers (1)

Stephen C
Stephen C

Reputation: 719596

The entries in a directory are not traversed in any particular order.

  • B is a traversal that visits x/y before x/a

  • C is a traversal that visits x/a before x/y

Both are possible, since the relevant javadocs place no constraints on the order in which the entries of a directory are visited. (The issue is not mentioned.)

And the Java tutorial says:

"A file tree is walked depth first, but you cannot make any assumptions about the iteration order that subdirectories are visited."

Emphasis added.


In practice, the traversal order will be deterministic provided that the parent directory (x) is not updated. It typically depends on how the order in which the directory entries are stored on disk.

Also note that you don't normally notice this because command line utilities (e.g. ls and the shell itself) typically sort directory entry names before showing them to you.

Upvotes: 2

Related Questions