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
  • 166,747
  • 40
  • 210
  • 420
Edward Yu
  • 736
  • 1
  • 6
  • 14

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
  • 155,977
  • 14
  • 207
  • 269
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
  • 32,598
  • 5
  • 75
  • 87