0

I have some variables defined like this.

public final static String pDrive = "\\\\fs-innova1\\projects\\";
public final static String hDrive = "\\\\fs-innova1\\hr-department\\";
public final static String iDrive = "\\\\fs-innova1\\innova\\";

Then later in my program I have a string that says "p:\blah\blah\blah" I would like to look at the first char in that string and call the variable like Char(0)+"Drive

0

2 Answers 2

3

You should use a Map<String, String> instead:

private static final Map<String, String> DRIVE_MAPPINGS = new HashMap<>();

static {
    DRIVE_MAPPINGS.put("p", "\\\\fs-innova1\\projects\\");
    DRIVE_MAPPINGS.put("h", "\\\\fs-innova1\\hr-department\\");
    DRIVE_MAPPINGS.put("i", "\\\\fs-innova1\\innova\\");
}

Then use

String mapping = DRIVE_MAPPINGS.get(input.substring(0, 1));

(Alternatively, if you're really only ever going to want the key to be a single character, use a Map<Character, String> - it's the same idea.)

I would personally create an immutable map using Guava, but again the principle is the same - that would just make it obvious that you weren't going to change the contents of the map after construction.

Sign up to request clarification or add additional context in comments.

4 Comments

Nitpicking, but Java 6 EOL was Feb '13, might as well promote using the diamond notation. :)
Well, I agree about Guava, but if it's not on the classpath, Collections.unmodifiableMap() would already be a good thing.
@TC1: Done here as it lets me get it all on one line - but I think a lot of Java coders are still on 6 (or even 5).
@JonSkeet I know they are, I've seen 4 still in production, but of all the places, I think SO is on the top of the list to push knowledge of new features, especially since these make it more readable. :)
0

It is impossible to name variables at runtime. Your best bet is to use a map.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.