Does Java support associative arrays? [duplicate]

2020-06-18 00:55发布

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?

标签: java arrays
6条回答
一纸荒年 Trace。
2楼-- · 2020-06-18 00:58

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

查看更多
家丑人穷心不美
3楼-- · 2020-06-18 01:03

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

查看更多
叛逆
4楼-- · 2020-06-18 01:10

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.

查看更多
Melony?
5楼-- · 2020-06-18 01:15

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.

查看更多
霸刀☆藐视天下
6楼-- · 2020-06-18 01:17

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
查看更多
Viruses.
7楼-- · 2020-06-18 01:19

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

查看更多
登录 后发表回答