Java-15.7 Map (1)-using arrays to simulate the creation of Map
In this chapter, we will simulate Map using arrays and learn about the creation of Map.
1. What is Map?
Map, a ing table, also called an association array, maintains the association of "key-value.
2. Simulate Map using Arrays
package com.ray.ch15;import java.util.HashSet;import java.util.Set;public class Test
{public static void main(String[] args) {AssociativeArray
map = new AssociativeArray
(2);map.put("one", "1");map.put("two", "2");try {map.put("three", "3");} catch (Exception e) {System.out.println("too many objects");}for (String key : map.getKeySet()) {System.out.println(map.getByKey(key));}}}class AssociativeArray
{private Object[][] objects;private int index = 0;public AssociativeArray(int count) {objects = new Object[count][2];}public void put(K key, V value) {if (index >= objects.length) {throw new ArrayIndexOutOfBoundsException();}objects[index++] = new Object[] { key, value };}public Set
getKeySet() {Set
set = new HashSet
();for (int i = 0; i < objects.length; i++) {set.add((K) objects[i][0]);}return set;}@SuppressWarnings("unchecked")public V getByKey(K key) {V v = null;for (int i = 0; i < objects.length; i++) {if (objects[i][0] == key) {v = (V) objects[i][1];}}return v;}}
Output:
Too upload objects
2
1
The above Code uses arrays to simulate the creation of Map.
Explanation:
(1) The above uses an Object array as the underlying data storage structure
(2) get method through array assignment
(3) Implement the getKeyset and get methods by traversing the Array
Note:
The above code is the simplest implementation, without any optimization, and there are various problems. We will end the implementation of java in the future.
Summary: This chapter describes how to use arrays to simulate the creation of map.
This chapter is here. Thank you.