java – What is the point of creating an array of 0 elements


int[] indexOfTask = new int[0];

For what purpose is such a possibility supported by the compiler?


There is such an excellent book " Effective Java " by Joshua Bloch, which contains an extensive list of guidelines for designing and developing effective, reliable and maintainable programs. One of the recommendations sounds like "Return arrays and collections of zero length, not null". For example, the class has a listFiles () method that returns an array of directory files. Imagine how inconvenient it would be if he couldn't return a zero-length array for empty directories! I would have had to instead of the laconic

for (File file : dir.listFiles()) {


File[] files = dir.listFiles();
if (files != null) {
    for (File file : files) {
Scroll to Top