I want to add values to a HashMap
, which would be used by methods in the same class. I have two solutions:
- Adding all the values with
static
- When the first method is called, add the values
Solution #1:
private static Map<Character, String> codes = new HashMap<>();
static {
codes.put('A', ".-");
codes.put('B', "-...");
codes.put('C', "-.-.");
codes.put('D', "-..");
codes.put('E', ".");
codes.put('F', "..-.");
// ...
}
Solution #2:
boolean methodIsCalled = false;
public static char decode(String s) {
if(!methodIsCalled) {
addValues();
}
// ...
}
private static void addValues() {
codes.put('A', ".-");
codes.put('B', "-...");
codes.put('C', "-.-.");
codes.put('D', "-..");
codes.put('E', ".");
codes.put('F', "..-.");
// ...
}
Which one is the most efficient? Which one is the best practice?
Aucun commentaire:
Enregistrer un commentaire