4

What would be Java equivalent for php array like this:

$user = array("name" => "John", "email" => "john@mail.com");
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
bancer
  • 7,475
  • 7
  • 39
  • 58

7 Answers7

9

You can use a HashMap or a Hashtable. Not sure which one to use? Read the API or check out this question which discusses the pros and cons of each.

HashMap<String, String> map = new HashMap<String, String>();
map.put("name", "John");
map.put("email", "john@mail.com");
Community
  • 1
  • 1
Catchwa
  • 5,845
  • 4
  • 31
  • 57
  • IMHO Hashtable was replaced by HashMap in Java 1.2. It is retained for legacy support. – Peter Lawrey Dec 16 '10 at 22:12
  • @Peter - I tend to agree with you. I've changed my link to a SO question of HashMap vs Hashtable (which comes down on the side of HashMap) instead. – Catchwa Dec 16 '10 at 22:20
6

An implementation of the Map interface is the Java equivalent of an associative array, but it seems like what you really want is a User class with fields for name and email.

Nick
  • 2,827
  • 4
  • 29
  • 39
  • Thanks for your answer. I would have User class, of course. My idea is to have something like array with primitive types or strings so that I could pass that array to a class that does not know about the type of the original object. – bancer Dec 16 '10 at 22:35
6

Keep in mind that PHP's associative arrays keep track of the order they were inserted. So if you use foreach to iterate over their keys, you'll get them in the same order.

The closest Java equivalent is probably LinkedHashMap.

JW.
  • 50,691
  • 36
  • 115
  • 143
3

I would suggest you use LinkedHashMap. Its main advantage over HashMap its that it retains the order the keys were added. For HashMap they appear in a pseudo random order which makes reading them much harder.

Map<String, String> map = new LinkedHashMap<String, String>();
map.put("name", "John");
map.put("email", "john@mail.com");
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

It's called java.util.HashMap

Mchl
  • 61,444
  • 9
  • 118
  • 120
1
Map user = new HashMap();
user.put("name", "John");
user.put("email", "john@mail.com");
Alexander Wallin
  • 1,394
  • 10
  • 22