1

I'm a newbie in Java who used PHP before that. I want to define an array in Java with a key for each array entry like in PHP. For example, in PHP I would have this:

$my_arr = array('one'=>1, 'two'=>2, 'three'=>3);

How would I define this array in Java?

1
  • 1
    You may need to use java.util.Map Commented Jul 18, 2014 at 15:24

4 Answers 4

3

In Java, array indices are always of type int. What you are looking for is a Map. You can do it like this:

Map<String,Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
Sign up to request clarification or add additional context in comments.

Comments

2

Code:

import java.util.*;

public class HashMapExample     
{
    public static void main (String[] args)
    {
       Map<String,Integer> map = new HashMap<>();
       map.put("one", 1);
       map.put("two", 2);
       map.put("three", 3);

      //how to traverse a map with Iterator 
      Iterator<String> keySetIterator = map.keySet().iterator();

      while(keySetIterator.hasNext()){
     String key = keySetIterator.next();
     System.out.println("key: " + key + " value: " + map.get(key));
       }
    }
}

Output:

key: one   value: 1
key: two   value: 2 
key: three value: 3

Source: For reading more take a look at this source

  1. http://java67.blogspot.com/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html

Tutorial for Itrators

2.http://www.java-samples.com/showtutorial.php?tutorialid=235

2 Comments

thanks sir. whats .iterator() and keySetIterator.next() for this HashMap
I put an tutorial for you, but basically they are used for traversing a map which is in this case is a hashmap. Or in better sense , you can access each element in the collection, one element at a time
2

What you need is a Map implementation, like HashMap.

Take a look on this tutorial, or the official Java tutorial for further details.

Comments

1

You can't do this with simple arrays with Java, simply because arrays are just simply containers.

Thankfully, there's a class that you can use that does exactly what you want:

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

For some tutorial, read : http://www.tutorialspoint.com/java/java_hashmap_class.htm

1 Comment

nice explantion but through an small sample so other vote you better

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.