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
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
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> students;10 private static Scanner in;11 {12 in = new Scanner(System.in);13 }14 15 public StuMap() {16 students = new HashMap<string>();17 18 }19 //省略方法,下面的方法会逐个列出20 }</string></string>
##>>>>>>>>>>>>>>> ;>>>>>>>>>>>>>>>>>>>>>>>>> ;>
Different from the List interface, adding objects to the Map uses theput(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 }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 }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>> entrySet =students.entrySet(); 6 for(Entry<string> entry:entrySet){ 7 System.out.println("取得建:"+entry.getKey()); 8 System.out.println("对应的值:"+entry.getValue().getName()); 9 10 }11 }</string></entry>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 <div class="cnblogs_code"></div>Code analysis:<p></p>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. <p>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! ! <span style="color: #0000ff"></span></p>2.keySet() method returns the Set collection of all keys. <p></p>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. <p></p>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 <p>getKey() and <span style="color: #000000">getValue()<span style="color: #000000"> Method to get the </span>"<strong>key<span style="color: #000000">" and "</span>value<span style="color: #000000">"</span></strong> of the key-value pair respectively. </span></p>Run results:<p></p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/001/ca5c3e6003aa37b1bbec91125be72157-1.png?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><hr> 3. Student course selection—Delete students in the Map<h2></h2>Delete key values in the Map Yes, the remove(object key) method is called. The following is an example of its use: <p></p><pre class="brush:php;toolbar:false"> 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 }Running results:
4. Student course selection - modifying students in the MapThere 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 }
1 if (map.containsKey(key)) {2 return map.put(key, value);3 } else4 return null;5
可以看出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 }
运行结果:
五、总结
Map -特点:元素成对出现,key-value,是映射关系,key不能重复,但value可以重复,也就是说,可以多key对一个value。支持泛型如Map
-实现类:HashMap是最常用的,HashMap中是无序排列,其元素中key或value可为null(但只能有一个为null)。
-声明(泛型)举例: 在类中声明 public Map xxx; 然后再构造方法中this.xxx = new HashMap
-获取:yy temp = xxx.get(key)
-添加:xxx.put( key(xx型), zz(yy型) );
-返回map中所有key(返回是set型集合形式) set xxxxx = xxx.keyset(); 用于遍历。
-返回map中所有entry对(key-value对)(返回是set型集合形式) set
-删除: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!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
