Home  >  Article  >  Java  >  What is map in java

What is map in java

(*-*)浩
(*-*)浩Original
2019-05-22 10:26:1521315browse

The map in java is a container that stores elements according to keys. Keys in a map can be objects of any type. There cannot be duplicate keys in the map, and each key has a corresponding value.

What is map in java

Map is a collection, a container that stores elements according to a key. The key is much like a subscript. In a List, the subscript is integer. Keys in Map can be objects of any type. There cannot be duplicate keys in the Map, and each key has a corresponding value.

(Recommended tutorial: java course)

A key (key) and its corresponding value constitute an element in the map collection.

The elements in Map are two objects, one object as key and one object as value. Keys cannot be repeated, but values ​​can.

Map itself is an interface. To use Map, you need to instantiate the object through a subclass.

There are the following commonly used methods in the Map interface:

What is map in java

Common subdivisions of the Map interface There are four classes: HashMap, HashTable, TreeMap, and ConcurrentHashMap.

For example:

public class Test{
	public static void main(String[] args) {
		Map<integer> map = new HashMap();
		map.put(1, "A");
		map.put(1, "A+");
		map.put(2, "B");
		map.put(3, "C");
		System.out.println(map);
		System.out.println(map.get(2));  //根据key取得value
		System.out.println(map.get(10));  //找不到返回null
		
		//取得Map中所有key信息
		Set<integer> set = map.keySet();
		Iterator<integer> iterator = set.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
	}</integer></integer></integer>

Note:

(1), the key value is not allowed to be repeated. If it is repeated, it will Update the corresponding value;

(2), both key and value are allowed to be null, and there is only one null key.

HashMap principle: When the amount of data is small (the threshold is 8 after JDK1.8), HashMap is stored in the linked list mode; when the amount of data becomes large, in order to perform quick search, the linked list will be changed into Save it as a red-black tree (balanced binary tree) and use hash to search.

Related learning recommendations: java introductory tutorial

The above is the detailed content of What is map in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn