3
$tagArray = array(
    "apples" => 12,
    "oranges" => 38,
    "pears" => 10,
    "mangos" => 24,
    "grapes" => 18,
    "bananas" => 56,
    "watermelons" => 80,
    "lemons" => 12,
    "limes" => 12,
    "pineapples" => 15,
    "strawberries" => 20,
    "coconuts" => 43,
    "cherries" => 20,
    "raspberries" => 8,
    "peaches" => 25
    );

How I can do this in Java, and how to calling for the first and second params?

0

1 Answer 1

13

Java has no built in support for associative arrays. The corresponding datastructure in java is a Map. In this case you could for instance make use of a HashMap.

Here's one way.

Map<String, Integer> tagArray = new HashMap<String, Integer>() {{
    put("apples", 12);
    put("oranges", 38);
    put("pears", 10);
    put("mangos", 24);
    put("grapes", 18);
    put("bananas", 56);
    put("watermelons", 80);
    put("lemons", 12);
    put("limes", 12);
    put("pineapples", 15);
    put("strawberries", 20);
    put("coconuts", 43);
    put("cherries", 20);
    put("raspberries", 8);
    put("peaches", 25);
}};

To get the value for, say, "lemons" you do

int value = tagArray.get("lemons");

As @Peter Lawrey points out in the comments: If the order in the array is important to you, you could use a LinkedHashMap instead of a HashMap.

Sign up to request clarification or add additional context in comments.

4 Comments

Too fast for me. ;) I would use a LinkedHashMap to retain order as you would in an array.
Wow, java has this kind of initialization now? I'm learning! Also, (@lacas) here's some info about it: c2.com/cgi/wiki?DoubleBraceInitialization
Ah, right, arrays are ordered as opposed to maps... I'll update my answer.
It's just an anonymous class. No magic. But a clever trick anyway ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.