[Java class set] _ notes for using the map interface (test instance)

Source: Internet
Author: User

[Java class set] _ notes for using the map interface

Objectives of this chapter:

Master the output operations of the map interface
Measure the test taker's knowledge about key class definition standards in the map interface.

Map interface output

For map interfaces, iterations (such as iterator and foreach) cannot be directly used for output, because each location in map stores a pair of values (key-> value), only one value can be found in iterator at a time. Therefore, if you need to use Iteration for output at this time, you must follow the steps below (take the iterator output method as an example ):

1. Change the map instance to the set interface object through the entryset () method.
2. instantiate iterator through the set interface instance
3. Iterative output through iterator. Each content is a map. Entry object.
4. Separate key-> value using map. Entry

However, it must be noted before the operation that the map interface is generally used only for search, and the output is a minority after all.

import java.util.HashMap;import java.util.Map;import java.util.Set;import java.util.Iterator;public class IteratorDemo04{    public static void main(String args[]){        Map<String,String> map = null;        map = new HashMap<String,String>();        map.put("mldn","www.mldn.cn");        map.put("zhinangtuan","www.zhinangtuan.cn");        map.put("mldnjava","www.mldnjava.cn");        Set<Map.Entry<String,String>> allSet = null;        allSet = map.entrySet();        Iterator<Map.Entry<String,String>> iter = null;        iter = allSet.iterator();        while(iter.hasNext()){            Map.Entry<String,String> me = iter.next();            System.out.println(me.getKey()+"-->"+me.getValue());        }    }}

Output:
Zhinangtuan --> www.zhinangtuan.cn
Mldn --> www.mldn.cn
Mldnjava --> www.mldnjava.cn

First, use iterator. Of course, you can also use foreach after jdk1.5.

import java.util.HashMap;import java.util.Map;import java.util.Set;import java.util.Iterator;public class IteratorDemo04{    public static void main(String args[]){        Map<String,String> map = null;        map = new HashMap<String,String>();        map.put("mldn","www.mldn.cn");        map.put("zhinangtuan","www.zhinangtuan.cn");        map.put("mldnjava","www.mldnjava.cn");        Set<Map.Entry<String,String>> allSet = null;        for(Map.Entry<String,String> me:map.entrySet()){            System.out.println(me.getKey()+"-->"+me.getValue());        }    }}

Output:
Zhinangtuan --> www.zhinangtuan.cn
Mldn --> www.mldn.cn
Mldnjava --> www.mldnjava.cn

The two output forms are actually output in the form of collection, but map. Entry is used as the content operation type.
In map, any type can be used as the key and value, so non-system classes can also be used.

Import Java. util. map; import Java. util. hashmap; class person {private string name; private int age; Public Person (string name, int age) {This. name = Name; this. age = age;} Public String tostring () {return "name:" + this. name + "; age:" + this. age ;}} public class hashmapdemo05 {public static void main (string ARGs []) {Map <string, person> map = NULL; Map = new hashmap <string, person> (); map. put (new person ("Zhang San", 30), "zhangsan"); // Add the content system. out. println (map. get (new person ("James", 30 )));}}

In this case, the custom class is used as the key, but the value cannot be obtained and the returned result is null. Why is the previous string acceptable, but does the custom class not exist?

In fact, for the matching process, there is a feature that the content can be queried only when the object is the same.

Import Java. util. map; import Java. util. hashmap; class person {private string name; private int age; Public Person (string name, int age) {This. name = Name; this. age = age;} Public String tostring () {return "name:" + this. name + "; age:" + this. age ;}} public class hashmapdemo06 {public static void main (string ARGs []) {Map <person, string> map = NULL; Map = new hashmap <person, string> (); person per = new person ("Zhang San", 30); map. put (Per, "zhangsan"); // Add the content system. out. println (map. get (PER ));}}

Output:
Zhangsan

However, this is not a solution, because it is impossible to take the person's per object everywhere. Like a string, the content can be found in the form of an anonymous object. In this case, the method is overwritten according to the method used to judge duplicate elements in the Set interface.

Note: Use a non-system class as the key directly.

To use a non-system class as the map key, this class must overwrite the following two methods in the object class:
Hashcode ()
Equals ()

Import Java. util. map; import Java. util. hashmap; class person {private string name; private int age; Public Person (string name, int age) {This. name = Name; this. age = age;} Public String tostring () {return "name:" + this. name + "; age:" + this. age;} public Boolean equals (Object OBJ) {If (this = OBJ) {return true;} If (! OBJ instanceof person) {return false;} person per = (person) OBJ; If (this. name. equals (Per. name) & this. age = per. age) {return true;} else {return false;} public int hashcode () {return this. name. hashcode () * This. age ;}} public class hashmapdemo07 {public static void main (string ARGs []) {Map <person, string> map = NULL; Map = new hashmap <person, string> (); map. put (new person ("Zhang San", 30), "zhangsan"); // Add the content system. out. println (map. get (new person ("James", 30 )));}}

Output:
Zhangsan

When it is used as a key or more accurately as an object, it actually relies on hashcode () and equals () to determine whether two anonymous objects are equal, which is automatically completed by the system content.

Summary:
1. MAP can use iterative output
Map-> entryset-> set-> iterator-> map. Entry-> key and Value
2. If a non-system class is used as the key, the equals and hashcode () methods must be overwritten. Otherwise, the method is invalid.

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.