Harry Joy
Harry Joy

Reputation: 59670

Java code equivalent to following php code

What could be the java equivalent code for following php syntax:

   $newPerson = array(
        'firstname'  => 'First',
        'lastname'   => 'Last',
        'email'      => '[email protected]',
    );

I think here firstname is index of array and First is value at that index.How can I define such an array in java?

Upvotes: 3

Views: 210

Answers (5)

Yagnesh Agola
Yagnesh Agola

Reputation: 4649

You should also use SortedMap to store value with user-define index name in sorted order
here is sample code to do this
define a SortedMap with:

SortedMap<String, String>newPerson = new TreeMap<String, String>();

to put value in shorted-map used:
newPerson.put("firstname", "First");

and to get this value :
newPerson.get(""firstname");

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502016

I suspect the closest you'll come is a map:

Map<String, String> map = new HashMap<String, String>();
map.put("firstname", "First");
map.put("lastname", "Last");
map.put("email", "[email protected]");

EDIT: If you want to preserve insertion order (i.e. you need to know that firstname was added before lastname) then you might want to use LinkedHashMap instead.

Upvotes: 2

Petar Ivanov
Petar Ivanov

Reputation: 93050

Map<String, String> newPerson = new HashMap<String, String>();
newPerson.put("firstname", "First");
newPerson.put("lastname", "Last");
newPerson.put("email", "[email protected]");

Upvotes: 2

Eng.Fouad
Eng.Fouad

Reputation: 117607

Map<String, String> newPerson = new HashMap<String, String>()
{{
    put("firstname", "First");
    put("lastname", "Last");
    put("email", "[email protected]");
}};

Upvotes: 1

Foo Bah
Foo Bah

Reputation: 26271

newPerson would be a java hash map (java.util.HashMap<String,String>) and you would explicitly insert by using put

Upvotes: 2

Related Questions