Does Java support associative arrays? [duplicate]

2020-06-18 00:41发布

问题:

This question already has answers here:
Closed 3 years ago.

I'm wondering if arrays in Java could do something like this:

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

I know I've seen similar features in other languages, but I'm not really familiar with any specifics... Just that there are ways to associate values with string constants rather than mere numeric indexes. Is there a way to achieve such a thing in Java?

回答1:

I don't know a thing about C++, but you are probably looking for a Class implementing the Map interface.



回答2:

You can't do this with a Java array. It sounds like you want to use a 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


回答3:

What you need is java.util.Map<Key, Value> interface and its implementations (e.g. HashMap) with String as key



回答4:

To store things with string keys, you need a Map. You can't use square brackets on a Map. You can do this in C++ because it supports operator overloading, but Java doesn't.

There is a proposal to add this syntax for maps, but it will be added for Java 8 at the earliest.



回答5:

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

Roughly speaking, usage would be:

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

etc.



回答6:

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