therealccarter therealccarter - 3 months ago 13
Java Question

How to set variable name with a string? Java/Android

I'm creating some file references and I need to be able to set the file names to

arbitraryName + "1"
(so that it is
arbitraryName1
)

For example:

File file1 = new File(getDir());


I can't hardcode
"file"
because that changes depending on other variables passed in.

Is there a way to do something like this?:

File fileName + "1" = new File(getDir());


So that I can then access it like this:

if(fileName1.exists()){

}

Answer

If you want to use a variable number of keyed elements with dynamically generated keys, instead of creating variables with dynamically generated names (it's not really possible, it is possible to create classes with dynamically generated elements but requires tons of hacking), just use a plain old Map:

 Map<String, File> myFiles = new HashMap<>();

Then, you can do:

myFiles.put("fileName" + i, file);

EDIT: then, for your postulated problem, you can do:

for (File file : myFiles.values()) {
    if (file.exists()) { ... }
}

If the keys don't matter, you can even use a normal List instead of a Map.