Home  >  Article  >  Java  >  A brief introduction to Map&HashMapde

A brief introduction to Map&HashMapde

零下一度
零下一度Original
2017-07-23 17:44:021586browse

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 }

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

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     }
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<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     }
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     }
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     }
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     }

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

可以看出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<类型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:
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
Previous article:What is inheritance?Next article:What is inheritance?