Concept
How does a Java map store and retrieve key-value pairs?
ComputerScienceOne / Dynamic Data Structures
"Finally, Java also supports a Map data structure which allows you to store key-value pairs. The keys and values can be any object type and are specified by two parameters when you create the map. A common implementation is the HashMap.\n\n1 //define a map that maps integers (keys) to strings (values):\n\n2 Map<Integer, String> numbers = new HashMap<Integer, String>();\n\n3\n\n4 //add key-value pairs:\n\n5 numbers.add(10, \"ten\");\n\n6 numbers.add(20, \"twenty\");\n\n7\n\n8 //retrieve values given a key:\n\n9 String name = numbers.get(20); //name equals \"twenty\"\n\n10\n\n11 //invalid mappings result in null:\n\n12 name = numbers.get(30); //name is null\n\nThe Collections library is much more extensive than what we’ve presented here. It includes implementations of stacks, queues, hash tables, balanced binary search trees, and many other dynamic data structure implementations."
Related Ideas
- How do Java lists provide dynamic data structures?ComputerScienceOne · Dynamic Data Structures
- How do equals() and hashCode() define object equality in Java?ComputerScienceOne · Common Methods
- How can you create arrays and collections of strings in Java?ComputerScienceOne · Comparisons
- How does Java use variables and collections in enhanced for loops?ComputerScienceOne · Enhanced For Loops
- How does Java perform binary searches on arrays and lists?ComputerScienceOne · Sorted Collections
- What dynamic data structures does the C standard library provide?ComputerScienceOne · Dynamic Data Structures
- How does Java handle passing primitive and object types to methods?ComputerScienceOne · Passing By Reference
- How do you compare strings in Java?ComputerScienceOne · Comparisons