Java learning notes 32 (set framework 6: Map interface), learning notes map

Source: Internet
Author: User

Java learning notes 32 (set framework 6: Map interface), learning notes map

The Map interface is different from the Collection interface:

The Collection elements in the Collection are isolated and can be considered single. They are stored one by one, called a single column set.

The Set elements in Map exist in pairs, which can be understood as husband and wife. They are saved in a pair, called a double row set.

Stored in Map: Key-value pairs. Duplicate keys and values are allowed.

 

Common set in the Map interface:

1. HashMap: The storage structure of the hash table, but the access sequence cannot be guaranteed.

2. LinkedHashMap: hash tables and linked lists are used to store data, which can be sequential.

 

Common Map interface methods:

Example:

Package demo; import java. util. hashMap; import java. util. map; public class MapDemo {public static void main (String [] args) {function1 (); function2 (); function3 ();} public static void function1 () {// store key-value pairs to Map <String, Integer> map = new HashMap <String, Integer> (); map. put ("a", 1); map. put ("B", 2); map. put ("c", 3); map. put ("c", 4); System. out. println (map); // {B = 2, c = 4, a = 1} // = connect key-value pair, save it to the duplicate key, it will overwrite} public static void function2 () {// obtain the value Map <Integer, String> map = new HashMap <Integer, String> (); map. put (1, "a"); map. put (2, "B"); map. put (3, "c"); String value = map. get (1); System. out. println (value); // a // If yes, return the value. If no value exists, return null} public static void function3 () {// remove the key-value Pair Map in the set <Integer, string> map = new HashMap <Integer, String> (); map. put (1, "a"); map. put (2, "B"); map. put (3, "c"); map. remove (3); System. out. println (map); // {1 = a, 2 = B }}}

 

Map interface traversal:

Method 1:

Package demo; import java. util. hashMap; import java. util. iterator; import java. util. map; import java. util. set; public class MapDemo {public static void main (String [] args) {function1 (); function2 ();} public static void function1 () {Map <String, integer> map = new HashMap <String, Integer> (); map. put ("a", 1); map. put ("B", 2); map. put ("c", 3); map. put ("d", 4); Set <String> set = map. keySet (); Iterator <String> it = set. iterator (); while (it. hasNext () {String key = it. next (); Integer value = map. get (key); System. out. println (key + "<=>" + value) ;}} public static void function2 () {Map <String, Integer> map = new HashMap <String, integer> (); map. put ("a", 1); map. put ("B", 2); map. put ("c", 3); map. put ("d", 4); for (String key: map. keySet () {Integer value = map. get (key); System. out. println (key + "<=>" + value) ;}}// unordered output Traversal

 

Method 2 (based on ing ):

package demo;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;import java.util.Set;public class MapDemo {    public static void main(String[] args) {        Map<Integer, String> map = new HashMap<Integer, String>();        map.put(1, "a");        map.put(2, "b");        map.put(3, "c");        Set<Entry<Integer, String>> set = map.entrySet();        Iterator<Entry<Integer, String>> it = set.iterator();        while (it.hasNext()) {            Entry<Integer, String> entry = it.next();            Integer key = entry.getKey();            String value = entry.getValue();            System.out.println(key + "<==>" + value);        }    }}

 

Store custom objects:

 

package demo;public class Person {    private String name;    private int age;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public Person(String name, int age) {        super();        this.name = name;        this.age = age;    }    public Person() {        super();        // TODO Auto-generated constructor stub    }    @Override    public String toString() {        return "Person [name=" + name + ", age=" + age + "]";    }    @Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result + age;        result = prime * result + ((name == null) ? 0 : name.hashCode());        return result;    }    @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        Person other = (Person) obj;        if (age != other.age)            return false;        if (name == null) {            if (other.name != null)                return false;        } else if (!name.equals(other.name))            return false;        return true;    }}
Package demo; import java. util. hashMap; import java. util. map; import java. util. map. entry; // storage custom type public class HashMapDemo {public static void main (String [] args) {function1 (); function2 ();} public static void function1 () {// The HashMap <String, Person> map = new HashMap <String, Person> (); map is displayed when the custom type is used as the value. put ("a", new Person ("1", 20); map. put ("B", new Person ("2", 20); map. put ("c", new Person ("3", 20); // use two methods to traverse for (String key: map. keySet () {Person value = map. get (key); System. out. println (key + "<=>" + value) ;}for (Entry <String, Person> entry: map. entrySet () {String key = entry. getKey (); Person value = entry. getValue (); System. out. println (key + "<=>" + value) ;}} public static void function2 () {// The custom type is used as the key. // ensure the uniqueness of the key, hashcode and equals methods need to be rewritten. HashMap <Person, String> map = new HashMap <Person, String> (); map. put (new Person ("a", 20), "a"); map. put (new Person ("B", 20), "a"); map. put (new Person ("c", 20), "a"); map. put (new Person ("c", 20), "a"); // two types of traversal for (Person key: map. keySet () {String value = map. get (key); System. out. println (key + "<=>" + value) ;}for (Entry <Person, String> entry: map. entrySet () {System. out. println (entry. getKey () + "<=>" + entry. getValue ());}}}

 

LinkedHashMap set:

Package demo; import java. util. linkedHashMap; public class LinkedHashMapDemo {public static void main (String [] args) {LinkedHashMap <String, String> link = new LinkedHashMap <String, String> (); link. put ("1", "a"); link. put ("2", "a"); link. put ("3", "a"); link. put ("4", "a"); System. out. println (link); // {1 = a, 2 = a, 3 = a, 4 = a} // consistent access sequence }}

 

There is also a hashtable set under the set interface, but it is out of date and is now replaced by hashmap

However, pay attention to one problem:

HashMap allows the storage of null values. HashTable does not allow the storage of null values. Both do not allow the storage of null keys.

 

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.