Is there a data structure like an associative array in Java?

Asked

Viewed 1,038 times

9

Well, I’m wanting to name an Array of Strings in Java, but I wanted it to be, for example:

String[] symbols;

And could be declared so:

symbols["name"] = "Tiago";

I know there’s no such Array, but somehow, there’s a way?

  • Related: http://answall.com/questions/46570/cria-e-manipular-array-associativomultidimensional

1 answer

8


You can use the class HashMap to do this.

Example:

Map<String, Integer> vehicles = new HashMap<>();
vehicles.put("BMW", 5);
vehicles.put("Mercedes", 3);
vehicles.put("Audi", 4);
vehicles.put("Ford", 10);

See more about the interface Map, and the class HashMap in:

Hashmap

Map

  • 1

    That’s right, thanks man, exactly what I needed :D

  • Vinícius, I edited your answer to use Generics and link the javadocs of java 8. Here’s the tip for next time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.