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 does not have associative arrays yet. But instead you can use a hash map as an alternative.
I don't know a thing about C++, but you are probably looking for a Class implementing the Map interface.
Are you looking for the
HashMap<k,v>()
class? See the javadocs here.Roughly speaking, usage would be:
etc.
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.
You can't do this with a Java array. It sounds like you want to use a
java.util.Map
.What you need is
java.util.Map<Key, Value>
interface and its implementations (e.g.HashMap
) withString
as key