3

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?

1

5 Answers 5

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

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.

4 Comments

May be a LinkedHashMap<String, String> is even more closer?
@Narendra: Possibly. It depends on whether the order is preserved in a PHP - I don't know. Will edit.
Yes this php.net/manual/en/language.types.array.php says array is a ordered map.
@Narendra: Right, thanks. Have left it as "If you want" as the OP may not be interested in that.
1
Map<String, String> newPerson = new HashMap<String, String>()
{{
    put("firstname", "First");
    put("lastname", "Last");
    put("email", "[email protected]");
}};

Comments

0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.