0

In PHP, I can change the index and value of arrays.

$array = array("foo" => 54);

So then

$array["foo"] 

returns 54. How can I do this in Java?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Edward Yu
  • 776
  • 2
  • 6
  • 15

2 Answers2

6

The equivalent of PHP's associative array is a Map in Java. Both share the key-value pair implementation with the most commonly used implementation being HashMap

Map<String, Integer> map = new HashMap<>();
map.put("foo", 54);

System.out.println(map.get("foo")); // displays 54

Other implementations exist such as LinkedHashMap which preserves insertion order and TreeMap which is sorted according to the natural ordering of its keys.

Community
  • 1
  • 1
Reimeus
  • 158,255
  • 15
  • 216
  • 276
2

Use a map implementation to do exactly this:

Map<String, Integer> m = new HashMap<String, Integer>();
m.put("foo", 54);
m.get("foo"); // will yield 54
hd1
  • 33,938
  • 5
  • 80
  • 91