[Java study notes] Map interface and its implementation class

table of Contents

1. Features of Map Collection

2. Overview of the functions of the Map collection

2.1 Add function

2.2 Delete function

2.3 Judgment function

2.4 Length function

2.5 Get function

3. Traversal of Map collection

3.1 Find the value based on the key

3.2 Find the key and value of the object based on the key value

4. Overview of HashMap

4.1 HashMap Case 1: Key String Value String

4.2 HashMap Case 2: Key Integer Value String

4.3 HashMap Case 3: Key String Value Student

4.4 HashMap Case 4: Key Student Value String

5. Overview and use of LinkedHashMap

6. Overview of TreeMap

6.1 TreeMap case 1: The key is String and the value is String

6.2 TreeMap case 2: The key is Student and the value is String

7. Interview questions

7.1 The difference between Hashtable and HashMap?

7.2 Do List, Set, Map and other interfaces inherit from the Map interface?

7.3 What is the difference between Collection and Collections?


1. Features of Map Collection

  • An object that maps keys to values
  • A map cannot contain duplicate keys
  • Each key can only be mapped to at most one value

2. Overview of the functions of the Map collection

2.1 Add function

  • V put(K key,V value): add element

2.2 Delete function

  • V remove(Object key): Delete the key-value pair element according to the key, and return the value
  • void clear(): Remove all key-value elements

2.3 Judgment function

  • boolean containsKey(Object key): Determine whether the collection contains the specified key
  • boolean containsValue(Object value): Determine whether the collection contains the specified value
  • boolean isEmpty(): Determine whether the collection is empty

2.4 Length function

  • int size(): Returns the logarithm of key-value pairs in the collection

2.5 Get function

  • Set<K> keySet(): Get the set of all keys in the set
  • V get(Object key): Get the value according to the key
  • Collection<V> values(): Get the collection of all values ​​in the collection
  • Set<Map.Entry<K,V>> entrySet(): returns a collection of key-value pair objects

3. Traversal of Map collection

3.1 Find the value based on the key

The analysis steps are as follows:

  • Get all keys
  • Traverse the set of keys, get each key
  • Find the value based on the key

Part of the code is as follows:

// 创建集合对象
Map<String, String> map = new HashMap<String, String>();

// 向集合中添加元素
map.put("杨过", "小龙女");
map.put("杨康", "穆念慈");
map.put("郭靖", "黄蓉");
map.put("杨玄风", "梅超风");
		
// 获取集合中所有键的集合
Set<String> set = map.keySet();
// 遍历set,得到每一个key
for (String key : set) {
	// 根据键去找值
	String value = map.get(key);
	System.out.println(key + "---" + value);
}

3.2 Find the key and value of the object based on the key value

The analysis steps are as follows:

  • Get the collection of all key-value pairs
  • Loop through the collection of key-value pair objects to get each key-value pair object
  • Get the key and value according to the key-value pair object

Part of the code is as follows:

// 创建集合对象
Map<String, String> map = new HashMap<String, String>();

// 向集合中添加元素
map.put("杨过", "小龙女");
map.put("杨康", "穆念慈");
map.put("郭靖", "黄蓉");
map.put("杨玄风", "梅超风");
		
// 获取键值对对象的集合
Set<Map.Entry<String, String>> entrySet = map.entrySet();
// 循环遍历键值对对象的集合,得到每一个键值对对象
for (Map.Entry<String, String> entry : entrySet) {
	// 根据键值对对象得到键和值
	String key = entry.getKey();
	String value = entry.getValue();
	System.out.println(key + "---" + value);
}

4. Overview of HashMap

  • HashMap is an implementation of the Map interface based on the hash table.
  • The role of the hash table is to ensure the uniqueness of the key.
  • The bottom layer of the hash table structure depends on the hashcode() method and equals() method!

4.1 HashMap Case 1: Key String Value String

// 创建集合对象
HashMap<String, String> hm = new HashMap<String, String>();

// 向集合中添加元素
hm.put("allan", "男");
hm.put("bella", "女");
hm.put("zhangsan", "女");

// 遍历
// 获取所有键的集合
Set<String> set = hm.keySet();
for (String key : set) {
	// 根据键去找值
	String value = hm.get(key);
	System.out.println(key + "---" + value);
}

4.2 HashMap Case 2: Key Integer Value String

// 创建集合对象
HashMap<Integer, String> hm = new HashMap<Integer, String>();

// 向集合中添加元素
hm.put(28, "allan");
hm.put(2, "bella");
hm.put(28, "zhangsan");
hm.put(27, "allan");

// 遍历
// 获取所有键的集合
Set<Integer> set = hm.keySet();
for (Integer key : set) {
	// 根据键找值
	String value = hm.get(key);
	System.out.println(key + "---" + value);
}

4.3 HashMap Case 3: Key String Value Student

Student.java code:

public class Student {
	private String name;
	private int age;
	
	public Student() {
		super();
	}

	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}
// 创建集合对象
HashMap<String, Student> hm = new HashMap<String, Student>();

// 创建学生对象
Student s1 = new Student("allan", 27);
Student s2 = new Student("bella", 2);
Student s3 = new Student("zhangsan", 28);
Student s4 = new Student("allan", 27);

// 向集合中添加元素
hm.put("spring001", s1);
hm.put("spring006", s2);
hm.put("spring002", s3);
hm.put("spring008", s4);

// 遍历
// 获取所有键的集合
Set<String> set = hm.keySet();
for (String key : set) {
	Student s = hm.get(key);
	System.out.println(key + "---" + s.getName() + "---" + s.getAge());
}

4.4 HashMap Case 4: Key Student Value String

Requirement: If the values ​​of the member variables of the two objects are the same, they are the same object.

Analysis: HashMap is an implementation of the Map interface based on the hash table, and the bottom layer of the hash table relies on the hashcode() method and equals() method. These two methods are not overridden in the Student class, so the hashcode() and equals() methods of the Object class are used by default. At this time, the hash value of the student object is different, so all student objects will be output!

Solution: Rewrite the hashcode() method and equals() method in the Student class!

The Student.java code is as follows:

package com.hw.map02;

public class Student {
	private String name;
	private int age;
	
	public Student() {
		super();
	}

	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
}

The test code is as follows:

// 创建集合对象
HashMap<Student, String> map = new HashMap<Student, String>();
		
// 创建学生对象
Student s1 = new Student("貂蝉", 27);
Student s2 = new Student("王昭君", 30);
Student s3 = new Student("西施", 33);
Student s4 = new Student("杨玉环", 35);
Student s5 = new Student("貂蝉", 27);
		
// 添加元素
map.put(s1, "三国");
map.put(s2, "汉朝");
map.put(s3, "春秋战国");
map.put(s4, "唐朝");
map.put(s5, "隋朝");
		
// 获取集合中所有键的集合
Set<Student> set = map.keySet();
for (Student stu : set) {
	String value = map.get(stu);
	System.out.println(stu.getName() + "---" + stu.getAge() + "---" + value);
}

The results of the operation are as follows:

貂蝉---27---隋朝
西施---33---春秋战国
杨玉环---35---唐朝
王昭君---30---汉朝

5. Overview and use of LinkedHashMap

LinkedHashMap is the implementation of the hash table and link of the Map interface, with a predictable iteration sequence.

  • The uniqueness of the key is guaranteed by the hash table
  • The order of the keys is guaranteed by the linked list (the order of storage and retrieval is the same)

LinkedHashMap guarantees the insertion order of records. When traversing LinkedHashMap, the first record is inserted first!

Part of the code is as follows:

// 创建集合对象
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

// 向集合中添加元素
map.put("spring_001", "hello");
map.put("spring_003", "world");
map.put("spring_001", "javaee");
map.put("spring_002", "hello");
map.put("spring_003", "html");
map.put("spring_004", "javascript");

// 获取集合中键的集合
Set<String> set = map.keySet();
for (String key : set) {
	String value = map.get(key);
	System.out.println(key + "---" + value);
}

The results of the operation are as follows:

spring_001---javaee
spring_003---html
spring_002---hello
spring_004---javascript

6. Overview of TreeMap

TreeMap is an implementation of the Map interface based on a binary tree.

The key is a binary tree structure, which can guarantee the sorting and uniqueness of the key!

Let's look at two TreeMap cases!

6.1 TreeMap case 1: The key is String and the value is String

// 创建集合对象
// 当构造方法为空时,使用自然排序进行排序
TreeMap<String, String> tm = new TreeMap<String, String>();

// 向集合中添加元素
tm.put("liangchaowei", "刘嘉玲");
tm.put("dengchao", "孙俪");
tm.put("huangxiaoming", "杨颖");
tm.put("zhangjie", "谢娜");
tm.put("huangxiaoming", "范冰冰");

// 遍历
Set<String> set = tm.keySet();
for (String key : set) {
	String value = tm.get(key);
	System.out.println(key + "---" + value);
}

The results of the operation are as follows:

dengchao---孙俪
huangxiaoming---范冰冰
liangchaowei---刘嘉玲
zhangjie---谢娜

6.2 TreeMap case 2: The key is Student and the value is String

The Student.java code is as follows:

package cn.itcast_04;

public class Student {
	private String name;
	private int age;
	
	public Student() {
		super();
	}

	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	
}

The TreeMapDemo2.java code is as follows:

package com.hw.map02;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;

/**
 * TreeMap:键是二叉树结构,可以保证键的排序和唯一性
 * 
 * TreeMap<Student, String> 
 * 		键:Student 
 * 		值:String
 * 
 * 使用比较器排序,按照年龄从小到大排序
 * 
 * @author HW
 * 
 */
public class TreeMapDemo2 {
	public static void main(String[] args) {
		// 创建集合对象
		// 当一个方法的参数是接口时,真正需要的是该接口实现类的对象
		TreeMap<Student, String> tm = new TreeMap<Student, String>(new Comparator<Student>() {

					public int compare(Student s1, Student s2) {
						int num1 = s1.getAge() - s2.getAge();
						int num2 = (num1 == 0) ? (s1.getName().compareTo(s2
								.getName())) : num1;
						return num2;
					}
			
		});

		// 创建学生对象
		Student s1 = new Student("allan", 27);
		Student s2 = new Student("bella", 3);
		Student s3 = new Student("ella", 28);
		Student s4 = new Student("bella", 2);
		Student s5 = new Student("allan", 27);

		// 向集合中添加元素
		tm.put(s1, "男");
		tm.put(s2, "女");
		tm.put(s3, "女");
		tm.put(s4, "男");
		tm.put(s5, "女");
		
		// 获取集合中键的集合
		Set<Student> set = tm.keySet();
		for (Student stu : set) {
			String value = tm.get(stu);
			System.out.println(stu.getName() + "---" + stu.getAge() + "---" + value);
		}
	}
}

The results of the operation are as follows:

bella---2---男
bella---3---女
allan---27---女
ella---28---女

7. Interview questions

7.1 The difference between Hashtable and HashMap?

  • Hashtable: thread safety, low efficiency. Null keys and null values ​​are not allowed
  • HashMap: thread is not safe and efficient. Allow null keys and null values

7.2 Do List, Set, Map and other interfaces inherit from the Map interface?

  • List and Set do not inherit from the Map interface, they inherit from the Collection interface
  • The Map interface itself is a top-level interface

7.3 What is the difference between Collection and Collections?

  • Collection: It is the top-level interface of a single-column collection, with sub-interfaces List and Set.
  • Collections: is a tool class for collection operations, which are static methods, including methods for sorting and binary search on collections

Guess you like

Origin blog.csdn.net/weixin_44679832/article/details/105439510