Does Java support associative arrays?

I am wondering if arrays in Java can do something like this:

int[] a = new int[10]; a["index0"] = 100; a["index1"] = 100; 

I know that I saw similar functions in other languages, but I'm not very familiar with any specifics ... There are simply ways to associate values ​​with string constants, and not with numeric numeric indices. Is there any way to achieve such a thing in Java?

+6
java arrays
source share
6 answers

I don't know anything about C ++, but you're probably looking for a class that implements a map interface .

+3
source share

You cannot do this with a Java array. It looks like you want to use java.util.Map .

 Map<String, Integer> a = new HashMap<String, Integer>(); // put values into the map a.put("index0", 100); // autoboxed from int -> Integer a.put("index1", Integer.valueOf(200)); // retrieve values from the map int index0 = a.get("index0"); // 100 int index1 = a.get("index1"); // 200 
+17
source share

You need the java.util.Map<Key, Value> interface and its implementation (e.g. HashMap ) with String as a key

+2
source share

To store things with string keys, you need a map. You cannot use square brackets on a map. You can do this in C ++ because it supports operator overloading, but Java does not.

proposal to add this syntax for maps , but it will be added for Java 8 as soon as possible .

+2
source share

Are you looking for the class HashMap<k,v>() ? See javadocs here.

Roughly speaking, the use will be:

 HashMap<String, int> a = new HashMap<String,int>(); a.put("index0", 100); 

and etc.

0
source share

java does not yet have associative arrays. But instead, you can use a hash map as an alternative.

0
source share

All Articles