Table of Contents
1) Map interface
2 ) HashMap implementation class
2. Student selection - use Map to add students
Case Function Description" >Case Function Description
 五、总结
Home Java javaTutorial A brief introduction to Map&HashMapde

A brief introduction to Map&HashMapde

Jul 23, 2017 pm 05:44 PM
java frame gather

1. Introduction to Map&HashMap

1) Map interface

1. The Map interface provides a mapping relationship, in which elements are stored in the form of key-value pairs, which can quickly find values ​​based on Key. Key-value can be any object and exists as an object instance of Entry type.

2.Key cannot be repeated, and Value can be repeated. Key-value can be null, but only one key can be null.

3.Map supports generics, Map

4. Each key can only be mapped to one value at most

5.The Map interface provides different Methods for returning key value collections, value value collections and Entry (key value pairs) collections

6. By put,removeoperands

2 ) HashMap implementation class

1. The Entry objects in HashMap are arranged in an unordered manner. HashMap is an important implementation class of Map and is also the most commonly used. It is implemented based on the hash table

2 . Both the Key value and the value value can be null, but a HashMap can only have one map with a null key value (the key cannot be repeated)


2. Student selection - use Map to add students

Case Function Description

1. Manage student information through Map, where key is the student ID and value is the student object.

2. Enter student information through the keyboard

3. Add, delete, and query student information in the collection

First create a StuMap class to test the use of Map. As follows:

 1 /** 2  * 学生类的Map集合类 3  * 
 4  * @author acer 5  * 6  */ 7 public class StuMap { 8     // 用来承装学生类型对象 9     private Map<String, Student> students;10     private static Scanner in;11     {12         in = new Scanner(System.in);13     }14 15     public StuMap() {16         students = new HashMap<String, Student>();17 18     }19    //省略方法,下面的方法会逐个列出20 }
Copy after login

##>>>>>>>>>>>>>>> ;>>>>>>>>>>>>>>>>>>>>>>>>> ;>

Different from the List interface, adding objects to the Map uses the

put(key,value) method. The following is an example of use:

 1   /* 2      * 添加学生类 输入学生id, 3      * 判断是否被占用 若未被占用,则输入姓名,创建新的学生对象,并且把该对象添加到Map中 4      * 否则,则提示已有该id 5      */ 6     public void AddStu() { 7         System.out.println("请输入要添加的学生id:"); 8         String Id = in.next();// 接受输入的id 9         Student st=students.get(Id);10         if(st==null){11 12             System.out.println("请输入要添加的学生姓名:");13             String name = in.next();// 接受输入的name14             this.students.put(Id, new Student(Id, name));15         }else{16             System.out.println("此Id已被占用!");17         }18 19     }
Copy after login
Write a test function that prints output, such as:

 1 /* 2      * 打印学生类 3      * 
 4      */ 5     public void PrintStu() { 6         System.out.println("总共有"+this.students.size()+"名学生:"); 7         //遍历keySet 8         for (String s : this.students.keySet()) { 9             Student st=students.get(s);10             if(st!=null){11             System.out.println("学生:" + students.get(s).getId() + "," + students.get(s).getName());12             }13         }14     }
Copy after login
The above example uses Map

keySet() Return the Set collection of keys in the Map and then use if to judge the output . In the Map, you can also use the entrySet() method to return the keys in the Map Value pair Entry, such as:

 1 /* 2      * 通过entrySet方法遍历Map 3      */ 4     public void EntrySet(){ 5         Set<Entry<String, Student>> entrySet =students.entrySet(); 6         for(Entry<String, Student> entry:entrySet){ 7             System.out.println("取得建:"+entry.getKey()); 8             System.out.println("对应的值:"+entry.getValue().getName()); 9 10         }11     }
Copy after login
Finally, we use the main function to call these functions to see the effect

1 public static void main(String[] args) {2         StuMap stu = new StuMap();3         for (int i = 0; i < 3; i++) {4             stu.AddStu();5         }6         stu.PrintStu();7         stu.EntrySet();8     }
Copy after login
Code analysis:

1.student.get(ID) uses the get() method of Map to detect whether there is a student whose value is ID. If not, return null.

The case here is to set the key value in the Map to the student's ID value, so it can be detected in this way. If the key value is other attributes of the student, it is another matter! !

2.keySet() method returns the Set collection of all keys.

3.keyset() returns all the keys in the Map in the form of a set that can be received by the Set collection. The mapping in the HashMap is unordered.

3.Map can also use the entrySet() method to return the key-value pair Entry in the Map. Entry is also a Set collection. It can call

getKey() and getValue() Method to get the "key" and "value" of the key-value pair respectively.

Run results:


3. Student course selection—Delete students in the Map

Delete key values ​​in the Map Yes, the remove(object key) method is called. The following is an example of its use:

 1 /* 2      * 删除map中映射 3      */ 4     public void RemoveStu(){ 5         do{ 6         System.out.println("请输入要删除的学生id:"); 7         String Id = in.next();// 接受输入的id 8         Student st=students.get(Id); 9         if(st==null){10             System.out.println("此id不存在!");11             12         }else{13             this.students.remove(Id);14             System.out.println("成功删除"+st.getId()+","+st.getName()+"同学");15             break;16         }17         }while(true);18     }
Copy after login
Running results:


4. Student course selection - modifying students in the Map

There are two ways to modify the key-value pairs in the Map. The first is to use the

put method. In fact, it is put in the add method. The usage method is the same as add. The essence here is to use put to overwrite the original data, that is, to modify it.

 1 /* 2      * 利用put方法修改Map中的value值 3      */ 4     public void ModifyStu(){ 5         do{ 6             System.out.println("请输入要修改的学生id:"); 7             String Id = in.next();// 接受输入的id 8             Student st=students.get(Id); 9             if(st==null){10                 System.out.println("此id不存在!");11                 12             }else{13                 System.out.println("学生原来的姓名:"+st.getName()+",请输入修改后的姓名:");14                 String name = in.next();// 接受输入的name15                 st=new Student(Id,name);16                 this.students.put(Id,st);17                 System.out.println("成功修改!修改后的学生为:"+st.getId()+","+st.getName()+"同学");18                 break;19             }20             }while(true);21         22     }
Copy after login

In addition to using the put method, Map provides a method called replace. You know its meaning, which means "replacement". The replace method is used the same as the put method, because its internal source code is as follows:

1 if (map.containsKey(key)) {2      return map.put(key, value);3  } else4      return null;5
Copy after login

可以看出replace方法就是调用put方法来完成修改操作的,但是我们为了和添加put进行区分,最好在使用修改的时候用replace方法进行修改。这样的代码可读性和维护性就增强了。

那么使用replace修改Map中的value值如下:(推荐使用replace方法)

 1 /* 2      * 利用replace方法修改Map中的value值 3      */ 4     public void Modify(){ 5         do{ 6             System.out.println("请输入要修改的学生id:"); 7             String Id = in.next();// 接受输入的id 8             Student st=students.get(Id); 9             if(st==null){10                 System.out.println("此id不存在!");11                 12             }else{13                 System.out.println("学生原来的姓名:"+st.getName()+",请输入修改后的姓名:");14                 String name = in.next();// 接受输入的name15                 st=new Student(Id,name);16                 this.students.replace(Id, st);17                 System.out.println("成功修改!修改后的学生为:"+st.getId()+","+st.getName()+"同学");18                 break;19             }20             }while(true);21     }
Copy after login

运行结果:


五、总结

Map -特点:元素成对出现,key-value,是映射关系,key不能重复,但value可以重复,也就是说,可以多key对一个value。支持泛型如Map

-实现类:HashMap是最常用的,HashMap中是无序排列,其元素中key或value可为null(但只能有一个为null)。

-声明(泛型)举例: 在类中声明 public Map<类型1, 类型2> xxx; 然后再构造方法中this.xxx = new HashMap<类型1, 类型2();

-获取:yy temp = xxx.get(key)

-添加:xxx.put( key(xx型), zz(yy型) );

-返回map中所有key(返回是set型集合形式) set xxxxx = xxx.keyset(); 用于遍历。

-返回map中所有entry对(key-value对)(返回是set型集合形式) set> xxxxx = xxx.entrySet(); 同样用于遍历。 遍历时:for(Entry 元素: xxxxx)

-删除:xxx.remove(key);

-修改可以用put,当put方法传入的key存在就相当于是修改(覆盖);但是推荐使用replace方法!

The above is the detailed content of A brief introduction to Map&HashMapde. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

H5: Tools, Frameworks, and Best Practices H5: Tools, Frameworks, and Best Practices Apr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

See all articles