49 Map in Java

Поділитися
Вставка
  • Опубліковано 14 тра 2024
  • You can create a map using one of its three concrete classes: HashMap,
    LinkedHashMap, or TreeMap.
    Amap is a container object that stores a collection of key/value pairs. It enables fast retrieval, deletion, and updating of the pair through the key. A map stores the values along with the keys. The keys are like indexes. In List, the indexes are integers. In Map, the keys can be any objects. A map cannot contain duplicate keys. Each key maps to one value. A key and its corresponding value form an entry stored in a map
    TheHashMap class is efficient for locating a value, inserting an entry, and deleting an entry. LinkedHashMap extends HashMap with a linked-list implementation that supports an ordering of the entries in the map. The entries in a HashMap are not ordered, but the entries in a LinkedHashMap can be retrieved either in the order in which they were inserted into the
    map (known as the insertion order) or in the order in which they were last accessed, from least recently to most recently accessed (access order). The no-arg constructor constructs a LinkedHashMap with the insertion order. To construct a LinkedHashMap with the access order, use LinkedHashMap(initialCapacity, loadFactor, true).
    TheTreeMap class is efficient for traversing the keys in a sorted order. The keys can be sorted using the Comparable interface or the Comparator interface. If you create a TreeMap using its no-arg constructor, the compareTo method in the Comparable interface is used to compare the keys in the map, assuming that the class for the keys implements the
    Comparable interface. To use a comparator, you have to use the TreeMap(Comparator comparator) constructor to create a sorted map that uses the compare method in the comparator to order the entries in the map based on the keys.
    SortedMap is a subinterface of Map, which guarantees that the entries in the map are sorted. Additionally, it provides the methods firstKey() and lastKey() for returning the first and last keys in the map, and headMap(toKey) and tailMap(fromKey) for returning a portion of the map whose keys are less than toKey and greater than or equal to fromKey, respectively.
    Prior to Java 2, java.util.Hashtable was used for mapping keys with values.
    Hashtable was redesigned to fit into the Java Collections Framework with all its methods retained for compatibility. Hashtable implements the Map interface and is used in the same way as HashMap, except that the update methods in Hashtable are synchronized.

КОМЕНТАРІ •