Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to PHP's associative arrays in JAVA

In PHP I could use an array with strings as keys. eg $some_array["cat"] = 123; $some_array["dog"] = 456; I just switched to Java and I can't find a data structure capable of doing this. Is this possible?

like image 994
some guy Avatar asked Dec 21 '22 08:12

some guy


2 Answers

What you are describing is an associative array, also called a table, dictionary, or map.

In Java, you want the Map interface, and probably the HashMap class as the implementation.

Map<String, Integer> myMap = new HashMap<String, Integer>();
myMap.put("cat", 123);

Integer value = myMap.get("cat"); //123
like image 126
Mark Peters Avatar answered Dec 24 '22 02:12

Mark Peters


You would use one of the Map implementations such as HashMap to do that.

like image 23
dteoh Avatar answered Dec 24 '22 00:12

dteoh