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?

Bovine
  • 64
  • 9
DolDurma
  • 15,753
  • 51
  • 198
  • 377

4 Answers4

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);
Axel
  • 13,939
  • 5
  • 50
  • 79
2

What you need is a Map implementation, like HashMap.

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

rlegendi
  • 10,466
  • 3
  • 38
  • 50
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

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
  • 1
    thanks sir. whats `.iterator()` and `keySetIterator.next()` for this `HashMap` – DolDurma Jul 18 '14 at 15:34
  • 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 – Kick Buttowski Jul 18 '14 at 15:35
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