What is the Java equivalent of this JavaScript code?
I've looked into ArrayLists and Arrays but cannot figure how to do something like this. The length isn't fixed and it's dynamically created.
In JavaScript, this is an object and it's properties.
var values = {
a:1,
b:2,
c:3,
d:4,
e:5,
f:6,
g:7,
h:8,
i:9,
j:10
}
console.log(values.j) //Output 10
console.log(values['j']) //Output 10
CodePudding user response:
I would use HashMap for that :
import java.util.HashMap;
public class MyProgram
{
public static void main(String[] args)
{
HashMap<String, Integer> values = new HashMap<String, Integer>();
values.put("a",1);
values.put("b",2);
values.put("c",3);
values.put("d",4);
values.put("e",5);
values.put("f",6);
values.put("g",7);
values.put("h",8);
values.put("i",9);
values.put("j",10);
System.out.println(values.get("j")); //Output 10
}
}
Do not forget import java.util.HashMap;
at the beginning
CodePudding user response:
Here is the code for it, since it's a good bit different to JavaScript's objects:
// you can't use primitive types, like int, char, float...
HashMap<Character, Integer> values = new HashMap<>();
values.put('a', 1);
values.put('b', 2);
values.put('c', 3);
values.put('d', 4);
values.put('e', 5);
values.put('f', 6);
System.out.println("value of 'f': " values.get('b'));