What would be Java equivalent for php array like this:
$user = array("name" => "John", "email" => "john@mail.com");
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");
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.
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.
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");
Try http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html, or more specifically a http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html.
Map user = new HashMap();
user.put("name", "John");
user.put("email", "john@mail.com");