开发者

Does Java support associative arrays? [duplicate]

开发者 https://www.devze.com 2023-02-10 04:30 出处:网络
This question already has answers here: Java associative-array (15 answers) Closed 5 years ago. I\'m wondering if arrays in Java could do something like this:
This question already has answers here: Java associative-array (15 answers) Closed 5 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开发者_StackOverflow社区 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?


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


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


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


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消