-3

I have this method to search for files and store them into a list and return it. The problem is that I get an "This method must return a result of type List" even I have a return statement of type List at the end of it.

public List<String> cautaFisiere(String root) {
    List<String> list = new ArrayList<String>();
    File[] file = new File(root).listFiles();
    if (file == null) {
        return ;
    }
    for (File x : file) {
        if (x.getName().toLowerCase().contains(fileName.toLowerCase())) {
            System.out.println(x.getName() + " " + x.getPath());
        }
        String path = x.getPath();
        if (x.isDirectory()) {
            cautaFisiere(path);

        }

    }
    return list;
}

the error is on the 5th line in my code

alin dradici
  • 201
  • 2
  • 4
  • 11

4 Answers4

2

You can fix that by returning null.

 if (file == null) {
    return null;
 }

Edit: I suppose you're right.

if (file == null) {
   return list;
}
Rauno
  • 616
  • 8
  • 22
2
public List<String> cautaFisiere(String root) {
  ...
  List<String> list = new ArrayList<String>();
  ...

    if (file == null) {
        return ;
    }
  ...
}

is not legal as the method should return a List of String.

So you could write :

if (file == null) {
    return null ;
}

or

if (file == null) {
    return list;
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

Your return statement currently does not return anything. Make it return an empty list

Jack Bishop
  • 115
  • 1
  • 7
0

This is a better solution:

if (file == null) {
    return list;
}

If you return null then the caller has to deal with the null as a special case. An empty list (which is what list is at that point) can be treated (pretty much) the same way as a non-empty list.

As @Ted Hopp suggests, throwing an exception would be another way to deal with this. It depends on whether you want / need to treat the case where the root directory is empty as exceptional / erroneous ... or as something that doesn't matter.

  • If you do want this to be "exceptional", it is a good idea.

  • If not, throwing an exception would be making unnecessary work for code further up the call stack.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216