12, "oranges" => 38, "pears" => 10, "mangos" => 24, "grapes" => 18, "banana...">

Convert php to java / android arrays

$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 can I do this in Java and how to call the first and second parameters?

+3
source share
1 answer

Java does not have native support for associative arrays. The corresponding data structure in java is Map. In this case, you could, for example, use HashMap.

Here is 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, let's say "lemons"you do

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

As @Peter Lawrey notes in the comments: if the order in the array is important to you, you can use LinkedHashMapinstead HashMap.

+13
source

Source: https://habr.com/ru/post/1781437/


All Articles