-1

I have an arrayList in a class and a getter for it. I need to make a method that returns an arrayList filled with all the files from the first arrayList that have the same name as the String arg. This is what I've come up with.

ArrayList<File> dirs = new ArrayList<File>(); // filled with files

public ArrayList<File> getDirectoriesNamed(String fileName) {
    ArrayList<File> files = new ArrayList<File>();
    for (File file : dirs) {
        if (file.getName() == fileName) //problem is here
            files.add(file);
    }
    return files;
}

however when I try this, I get an empty arrayList. and I figured out that the reason is because of the if Statement... is there any reason why that shouldn't work that I'm not seeing?

2 Answers2

0

You are comparing two Strings with '==', use file.getName().equals(fileName)

apines
  • 1,254
  • 14
  • 36
  • 5
    Just flag as duplicate. – takendarkk Dec 14 '14 at 04:56
  • Down voted because I have answered the correct answer but the question is a duplicate? Seems a bit unfair doesn't it? – apines Dec 14 '14 at 05:10
  • 1
    Yes it does, that's why I only left you a comment. However many people here very much frown upon answering questions like this that get asked many times per day and are (to most people) obvious duplicates. – takendarkk Dec 14 '14 at 05:13
-1

Two things...

1) Make sure you include the extensions, e.g filename.txt as you String fileName.

2) Objects should be compared with .equals() if it's a string and you are worried about caps there is .equalsIgnoreCase(). I am pretty sure == is not the issue for you here even though objects should be compared differently == in java does work for some string objects. NOTE that just because it works doesn't mean it is right.

Ya Wang
  • 1,758
  • 1
  • 19
  • 41