I want to create an object in Java, converting code from JavaScript, but I cannot find how to do so.
It's a really simple problem in JavaScript:
MINI_KEYS = ["1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F", "G", "H", "J",
"K", "L", "M", "N", "P", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"];
// Here is the object I want to create - a quick lookup of the array position of each letter
MINI_KEYS_INVERSE = {};
for (var i = 0; i < MINI_KEYS.length; i++) {
MINI_KEYS_INVERSE[MINI_KEYS[i]] = i;
}
This seems to be a really involved problem in Java requiring a declaration of a new class, etc.
How do you set up objects on the fly where you can write objectElement["stringEntry"] = (integer)
?
You don't.
You do declare a new class. Java objects cannot be created "on the fly" as you put it without having an associated class that describes their contents, including field names and types for each field, and in particular Java objects all have a fixed number of internal fields that cannot be added or subtracted to while the program executes.
This is a deliberate language design decision, part of Java being a strongly typed language. (In fairness, after you gain experience in Java, this will stop feeling like a "really involved problem" and instead think about problems in this more preemptively structured way, and consider creating classes as part of the usual process.)
In this particular case, I would use an explicit Map<String, Integer>
object that allows you to map string objects to integers, not necessarily a specific class; I would write something like
Map<String, Integer> miniKeysInverse = new HashMap<>();
for (int i = 0; i < MINI_KEYS.length; i++) {
miniKeysInverse.put(MINI_KEYS[i], i);
}