Java Collection framework (medium) and java Collection framework

Source: Internet
Author: User

Java Collection framework (medium) and java Collection framework
Java Collection framework (medium)

Because the collection framework in Java has a lot of content, it is divided into three parts to introduce the Java Collection framework, the content is from the shortest to the deep, if you already have a java-based partner, you can directly jump to the <shallow-in-depth Java Collection framework (below)>.

Contents

Java Collection framework (I)

Java Collection framework (medium)

Java Collection framework (lower)Try to catch up ..An update notification will be sent after you pay attention to it!

Preface

In <Java Collection framework (I)> Describes the basic operations of the List interface and Set interface. In this article, I will introduce the basic operations of the Map interface. In the <Java Collection framework (I)> The program used to simulate Students' Course Selection in. If you are not clear about it, you can read it first. <Java Collection framework (I)>.

1. Introduction to Map & HashMap 1) Map interface

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

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

3. Map supports generics. Map <K, V>

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

5. The Map interface provides methods to return the key value set, value set, and Entry (key-value Pair) set.

6. put <K key, V value>, remove <Object key> operations

2) HashMap implementation class

1. Entry objects in HashMap are arranged out of order. HashMap is an important implementation class of Map and is also the most commonly used. Based on the hash table, it is implemented.

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

Ii. Course Selection-use Map to add student cases

1. Use Map <String, Student> to manage Student information, 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 Set

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

1/** 2 * Map Collection class of Student class 3*4 * @ author acer 5*6 */7 public class StuMap {8 // used to hold the student type object 9 private Map <String, student> students; 10 private static tables in; 11 {12 in = new tables (System. in); 13} 14 15 public StuMap () {16 students = new HashMap <String, Student> (); 17 18} 19 // omitting the method, the following methods will list 20}

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Unlike the List interface, the put (key, value) method is used to add objects to Map. The following is an example:

1/* 2 * Add the student category and enter the student id. 3 * If the student is occupied or not, enter the name and create a new student object, and add this object to Map 4 * Otherwise, the System prompts that the id 5 */6 public void AddStu () {7 System. out. println ("Enter the student id to be added:"); 8 String Id = in. next (); // accept the input id 9 Student st = students. get (Id); 10 if (st = null) {11 12 System. out. println ("enter the name of the student to be added:"); 13 String name = in. next (); // accept the input name14 this. students. put (Id, new Student (Id, name); 15} else {16 System. out. println ("this Id has been occupied Yes! "); 17} 18 19}

Write another test function that prints the output, such:

1/* 2 * print Student Category 3*4 */5 public void PrintStu () {6 System. out. println ("Total" + this. students. size () + "Student:"); 7 // traverse keySet 8 for (String s: this. students. keySet () {9 Student st = students. get (s); 10 if (st! = Null) {11 System. out. println ("Student:" + students. get (s ). getId () + "," + students. get (s ). getName (); 12} 13} 14}

In the above example, Map's keySet () is used to return the Set of keys in Map and then use if to judge the output. In Map, entrySet () can also be used () return the key-Value Pair Entry in Map, for example:

1/* 2 * traverse 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 ("Get build:" + entry. getKey (); 8 System. out. println ("corresponding value:" + entry. getValue (). getName (); 9 10} 11}

Finally, we use the main function to call these functions to see how they work.

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 check whether there are students whose values are ID. If not, null is returned. In this case, the key value in Map is set to the student ID value, so we can use this method to detect it. If the key value is other students, it is another matter !!

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

3. keyset () returns all the keys in the Map to be received by the Set in the form of a Set. The ing in the HashMap is unordered.

3. map can also use the entrySet () method to return the key-Value Pair Entry in Map. The Entry is also a Set. It can call the getKey () and getValue () methods to obtain the key-value pairs respectively."Key" and "value".

Running result:

3. Select a student course-delete the student in Map

Deleting a key-Value Pair in Map calls the remove (object key) method. The following is an example of its usage:

1/* 2 * Delete ing in map 3 */4 public void RemoveStu () {5 do {6 System. out. println ("Enter the student id to delete:"); 7 String Id = in. next (); // accept the input id 8 Student st = students. get (Id); 9 if (st = null) {10 System. out. println ("this id does not exist! "); 11 12} else {13 this. students. remove (Id); 14 System. out. println ("successfully deleted" + st. getId () + "," + st. getName () + "student"); 15 break; 16} 17} while (true); 18}

Running result:

4. Selecting Courses for students-modifying students in Map

There are two methods to modify key-value pairs in Map. The first method is to usePut Method. Actually, it is the put in the add method. The use method is similar to the add method. The essence here is to overwrite the original data with put, that is, to modify it.

1/* 2 * use the put Method to modify the value in Map 3 */4 public void ModifyStu () {5 do {6 System. out. println ("Enter the student id to be modified:"); 7 String Id = in. next (); // accept the input id 8 Student st = students. get (Id); 9 if (st = null) {10 System. out. println ("this id does not exist! "); 11 12} else {13 System. out. println ("original student name:" + st. getName () + ", enter the modified name:"); 14 String name = in. next (); // accept the input name15 st = new Student (Id, name); 16 this. students. put (Id, st); 17 System. out. println ("modified successfully! The modified student is: "+ st. getId () + "," + st. getName () + "Classmate"); 18 break; 19} 20} while (true); 21 22}

In addition to the put method, Map provides a method called replace, which is known as "replace. The replace method is 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  

We can see that the replace method calls the put Method to complete the modification operation. However, to distinguish it from the added put method, it is best to use the replace method to modify the modification. This enhances code readability and maintainability.

Modify the value in Map using replace as follows:(The replace method is recommended)

1/* 2 * use the replace method to Modify the value in Map 3 */4 public void Modify () {5 do {6 System. out. println ("Enter the student id to be modified:"); 7 String Id = in. next (); // accept the input id 8 Student st = students. get (Id); 9 if (st = null) {10 System. out. println ("this id does not exist! "); 11 12} else {13 System. out. println ("original student name:" + st. getName () + ", enter the modified name:"); 14 String name = in. next (); // accept the input name15 st = new Student (Id, name); 16 this. students. replace (Id, st); 17 System. out. println ("modified successfully! The modified student is: "+ st. getId () + "," + st. getName () + "Classmate"); 18 break; 19} 20} while (true); 21}

Running result:

V. Summary

Map-Features: Key-value pairs appear in pairs, which are ing relationships. Keys cannot be repeated, but values can be repeated. That is, multiple keys can be used for one value. Supports generics such as Map <yy1, yy2>.

-Implementation class: HashMap is the most commonly used. In HashMap, It is unordered. The key or value in its element can be null (but only one of them can be null ).

-Declaration (generic) Example: Declare public Map <Type 1, type 2> xxx in the class; then construct this. xxx = new HashMap <Type 1, type 2 ();

-Obtain: Yy temp = xxx. get (key)

-Add: Xxx. put (key (xx type), zz (yy type ));

-Returns all the keys in the map (in the set form)Set xxxxx = xxx. keyset (); For traversal.

-Returns all the entry pairs (key-value pairs) in the map)(The returned result is a set type.) set <Entry <xx, yy> xxxxx = xxx. entrySet (); is also used for traversal. Time Duration: for (Entry <xx, yy> element: xxxxx)

-Delete: Xxx. remove (key );

-Modify:You can use put. When the key passed in by put method exists, it is equivalent to modifying (overwriting). However, the replace method is recommended!

This chapter mainly introduces the basic operations of the Map interface and sends the next notice: What should I do if the basic operations of the set are insufficient? How can I determine whether an element object in a set exists? How to sort the List set? Are these problems bothering you? In the next article, the blogger will introduce other members of the java Collection framework to address these problems.Follow~~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.