Android java util map

Android java util map

This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.

The Map interface provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map’s collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.

All general-purpose map implementation classes should provide two «standard» constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the JDK comply.

The «destructive» methods contained in this interface, that is, the methods that modify the map on which they operate, are specified to throw UnsupportedOperationException if this map does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the map. For example, invoking the putAll(Map) method on an unmodifiable map may, but is not required to, throw the exception if the map whose mappings are to be «superimposed» is empty.

Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.

This interface is a member of the Java Collections Framework.

Источник

Android java util map

A Map is a data structure consisting of a set of keys and values in which each key is mapped to a single value. The class of the objects used as keys is declared when the Map is declared, as is the class of the corresponding values.

A Map provides helper methods to iterate through all of the keys contained in it, as well as various methods to access and update the key/value pairs.

Summary

Nested Classes
Map.Entry Map.Entry is a key/value mapping contained in a Map .

Public Methods

public abstract void clear ()

Removes all elements from this Map , leaving it empty.

Throws
Public Methods
UnsupportedOperationException if removing elements from this Map is not supported.
See Also

public abstract boolean containsKey (Object key)

Returns whether this Map contains the specified key.

Parameters
Returns
  • true if this map contains the specified key, false otherwise.

public abstract boolean containsValue (Object value)

Returns whether this Map contains the specified value.

Parameters
Returns
  • true if this map contains the specified value, false otherwise.

public abstract Set > entrySet ()

Returns a Set containing all of the mappings in this Map . Each mapping is an instance of Map.Entry . As the Set is backed by this Map , changes in one will be reflected in the other.

Returns

public abstract boolean equals (Object object)

Compares the argument to the receiver, and returns true if the specified object is a Map and both Map s contain the same mappings.

Parameters
object the Object to compare with this Object .
Returns
  • boolean true if the Object is the same as this Object false if it is different from this Object .
See Also

public abstract V get (Object key)

Returns the value of the mapping with the specified key.

Parameters
Returns
  • the value of the mapping with the specified key, or null if no mapping for the specified key is found.

public abstract int hashCode ()

Returns an integer hash code for the receiver. Object s which are equal return the same value for this method.

Returns
See Also

public abstract boolean isEmpty ()

Returns whether this map is empty.

Returns
  • true if this map has no elements, false otherwise.
See Also

public abstract Set keySet ()

Returns a set of the keys contained in this Map . The Set is backed by this Map so changes to one are reflected by the other. The Set does not support adding.

Returns

public abstract V put (K key, V value)

Maps the specified key to the specified value.

Parameters
Returns
  • the value of any previous mapping with the specified key or null if there was no mapping.
Throws
UnsupportedOperationException if adding to this Map is not supported.
ClassCastException if the class of the key or value is inappropriate for this Map .
IllegalArgumentException if the key or value cannot be added to this Map .
NullPointerException if the key or value is null and this Map does not support null keys or values.

public abstract void putAll (Map map)

Copies every mapping in the specified Map to this Map .

Parameters
map the Map to copy mappings from.
Throws
UnsupportedOperationException if adding to this Map is not supported.
ClassCastException if the class of a key or a value of the specified Map is inappropriate for this Map .
IllegalArgumentException if a key or value cannot be added to this Map .
NullPointerException if a key or value is null and this Map does not support null keys or values.

public abstract V remove (Object key)

Removes a mapping with the specified key from this Map .

Parameters
key the key of the mapping to remove.
Returns
  • the value of the removed mapping or null if no mapping for the specified key was found.
Throws
UnsupportedOperationException if removing from this Map is not supported.

public abstract int size ()

Returns the number of mappings in this Map .

Returns
  • the number of mappings in this Map .

public abstract Collection values ()

Returns a Collection of the values contained in this Map . The Collection is backed by this Map so changes to one are reflected by the other. The Collection supports remove(Object) , )»>removeAll(Collection ) , )»>retainAll(Collection ) , and clear() operations, and it does not support add(E) or )»>addAll(Collection ) operations.

This method returns a Collection which is the subclass of AbstractCollection . The iterator() method of this subclass returns a «wrapper object» over the iterator of this Map ‘s entrySet() . The size() method wraps this Map ‘s size() method and the contains(Object) method wraps this Map ‘s containsValue(Object) method.

The collection is created when this method is called at first time and returned in response to all subsequent calls. This method may return different Collection when multiple calls to this method, since it has no synchronization performed.

Источник

Android java util map

This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.

The Map interface provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map’s collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.

All general-purpose map implementation classes should provide two «standard» constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the JDK comply.

The «destructive» methods contained in this interface, that is, the methods that modify the map on which they operate, are specified to throw UnsupportedOperationException if this map does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the map. For example, invoking the putAll(Map) method on an unmodifiable map may, but is not required to, throw the exception if the map whose mappings are to be «superimposed» is empty.

Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.

Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the containsKey(Object key) method says: «returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k)).» This specification should not be construed to imply that invoking Map.containsKey with a non-null argument key will cause key.equals(k) to be invoked for any key k. Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two keys. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying Object methods wherever the implementor deems it appropriate.

Some map operations which perform recursive traversal of the map may fail with an exception for self-referential instances where the map directly or indirectly contains itself. This includes the clone() , equals() , hashCode() and toString() methods. Implementations may optionally handle the self-referential scenario, however most current implementations do not do so.

This interface is a member of the Java Collections Framework.

Источник

Android java util map

Как уже было сказано во введении, интерфес java.util.Map не имеет отношения к интерфейсу java.util.Collection , однако формально является коллекцией.

По сути, это коллекция пар ключ -> значение, а java.util.Map это интерфейс ассоциативного массива. Каждому ключу соответствует некоторое значение. Иногда реализации java.util.Map называют ‘мапами’, хэш-таблицами, в Python же это и вовсе словари .

Название Map появилось как сокращение слова mapping , что значит отображение , соответствие .

В интерфейсе java.util.Map параметризуются два типа, это ключ и значение.

Объявление java.util.Map выглядит как:

При этом стоит отметить, что не может быть повторяющихся ключей, что следует из названия и смысла Map : каждому ключу соответствует значение.

Вопрос:

Почему бы тогда не назвать просто словарь , как в Python ?

Ответ:

На самом деле в Java существует абстрактный класс java.util.Dictionary еще с версии 1.0 , который сейчасс уже давно не используется.

И до этого иерархия как раз и была основана на классе java.util.Dictionary , например, как одна из старых реализаций хэш-таблицы — java.util.HashTable .

Класс java.util.Dictionary является полностью абтрактным, без какого-либо состояния.

Но благодаря WORA в Java просто так ничего не меняют и не удаляют, поэтому старые классы остались, а новую иерархию начали строить с интерфейсов.

Интерфейс java.util.Map появился в Java начиная с версии 1.2 .

Основные методы, которые предоставляет интерфейс java.util.Map :

  • V get(Object key)
  • V put(K key, V value)
  • int indexOf(Object element)
  • V remove(Object key)
  • Set keySet()
  • Collection values()
  • Set > entrySet()

Это значит, что все реализации интерфейса java.util.Map позволяют доставать, добавлять и удалять элементы по ключам, а также предоставлять множество ключей и коллекцию хранимых значений.

Отдельного рассмотрения заслуживает последний метод: Set > entrySet() .

Как уже было сказано выше, Map это набор пар ключ-значение.

Так вот интерфейс, описывающий поведение такой пары, называется Entry .

Объявление java.util.Map#Entry выглядит как:

И предоставляет методы, позволяющие получить/установить ключ и значение.

Единственное, что может быть здесь интересно — это то, что setValue в отличии от канонических setter- ов возвращает старое замененное значение.

Помимо всего прочего предоставляются также компараторы для сравнения пар по ключу и значению.

У каждого класса, реализующего интерфейс java.util.Map своя реализация java.util.Map#Entry , но большинство из них основано на стандартной реализации, которая объявлена у java.util.HashMap .

Объявление выглядит следующим образом:

В этой реализации нет каких-то подводных камней и сложностей, кроме того, что она объявлена с модификатором доступа package . Ее использование ограничено в рамках пакета, в классе которого она объявлена, т.е java.util .

Стандартная реализация, доступная для использования везде, объявлена у java.util.AbstractMap и называется SimpleEntry .

Объявление выглядит следующим образом:

Там же объявлена и неизменяемая реализация SimpleImmutableEntry . Также существуют сторонние реализации java.util.Map#Entry , например, в библиотеке Apache Commons .

Иерархия классов выглядит следующим образом:

Абстрактный класс java.util.AbstractMap предоставляет заготовку для последующих реализаций.

В нем уже определены некоторые методы, достаточные для неизменяемой структуры данных, но такие методы как put кидают исключение java.lang.UnsupportedOperationException .

Что говорит о том, что операция не поддерживется и ее надо либо не использовать, либо переопределить метод.

Наиболее известные реализации java.util.Map :

  • java.util.HashMap — основана на хэш-таблицах.
  • java.util.LinkedHashMap — расширение предыдущей реализации на основе двусвязных списков.
  • java.util.TreeMap — основана на красно-черном дереве.

Существует также реализация java.util.HashTable , но она уже давно не используется, во многом благодаря тому, что большинство методов в ней является synchronized , что губительо сказывается на производительности.

Когда и какую реализацию выбрать?

Если порядок хранения элементов не важен, то выбор java.util.HashMap более чем оправдан.

Данная реализация предоставляет отличную производительность работы с базовыми методами(добавление, поиск, удаление): O(1) , но при условии отсутствия коллизий, т.е хорошо определенной хэш-функции добавляемых элементов, в Java за это отвечает метод hashCode.

В случае, если порядок добавления элементов важен, то стоит рассмотреть java.util.LinkedHashMap . Понятно, что за сохранение порядка надо платить, поэтому данная реализация работает медленнее, чем java.util.HashMap .

Минусом может также являться то, что и java.util.HashMap , и java.util.LinkedHashMap занимают в памяти больше места, чем хранят элементов, в отличии от java.util.TreeMap .

Если необходимо, чтобы элементы были отсортированы, то следует присмотреться к java.util.TreeMap . Однако в таком случае добавляемые элементы должны либо реализовывать интерфейс java.lang.Comparable , либо необходимо написать свой собственный компаратор.

Помните, что java.util.TreeMap не поддерживает работу с null ключами.

Структура данных Производительность (basic ops) Память Отсортированность элементов Работа с null
Treemap O(log(N)) Без издержек В естественном порядке Недопустимы null ключи, без ограничений на null значения
HashMap O(1) С издержками Неотсортирован Допустим null ключ, без ограничений на null значения
Linked HashMap O(1) (но медленнее HashMap) Также как и в HashMap В порядке добавления Допустим null ключ, без ограничений на null значения

Реализации java.util.Map имеют встроенные итераторы. Получить можно как список всех ключей keySet() или всех значений values() , так и все пары ключ-значение entrySet() .

При этом следует помнить, что порядок гарантируеутся не всеми реализациями, как например в примере выше.

Стоит помнить, что, как и в случае с итерированием сипсков, если в ходе работы итератора структура данных была изменена (без использования методов итератора), то будет выброшено исключение:

Избежать этого можно удаляя элемент с помощью итератора, с которым происходит работа:

Источник

Читайте также:  Не включается планшет мой андроид
Оцените статью