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

Source: Internet
Author: User

[Java class set] _ map interface notes

Understanding the difference between the map interface and the collection Interface
Understanding the relationship between map and map. Entry Interfaces
Common map interfaces: hashmap, hashtable, treemap, and weekhashmap
Measure the test taker's knowledge about the differences between hashmap and hashtable.

3. Details

Collection operations have previously discovered that each time an object is saved, an object is saved, but a pair of objects are saved in map. objects are saved in the form of key-> value.
It's like a phone book: James-> 123456

Methods In the map interface

No. method or class type description
1 Public void clear () General clear map set
2 Public Boolean containskey (Object key) is used to determine whether the specified key exists.
3 Public Boolean containsvalue (object Value) is used to determine whether the specified value exists.
4 Public set <map. Entry <K, V> entryset () changes the map object to a set.
5 Public Boolean equals (Object O) Common Object comparison
6. Public v get (Object K) is used to obtain the value based on the key.
7 public int hashcode () Normal Return hash code
8 Public Boolean isempty () normal judgment set is empty
9 Public set <k> keyset () obtains all keys
10 public v put (K key, V value) add elements to the set
11 Public void putall (Map <? Extends K, extends v> T) Add the content in a map set to another map
12 public v remove (Object key) delete value according to key
13 public int size () Common get set length
14 public collection <v> values (): obtain all values

Common subclass of map interface:
Hashmap: it is stored unordered and is a new operation class. Duplicate keys are not allowed.
Hashtable: The operation class is unordered and the key cannot be repeated.
Treemap: A map set that can be sorted by keys in the set. Duplicate keys are not allowed.
Weakhashmap: a weak referenced map set. When some content in the set is no longer used, useless data can be clearly removed and can be recycled by GC.
Identityhashmap: a set of map keys that can be repeated.

Relationship between map and map. entry:

Take hashmap as an example to describe the operations of the basic map method.

Import Java. util. hashmap; import Java. util. map; public class hashmapdemo01 {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"); string val = map. get ("mldn"); system. out. println ("the retrieved content is:" + val );}}

Output: The retrieved content is www.mldn.cn.

In map, you can also use the containsxxx () method to determine whether the specified key or value exists.

Import Java. util. hashmap; import Java. util. map; public class hashmapdemo02 {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"); If (map. containskey ("mldn") {system. out. println ("the searched key exists! ");} Else {system. Out. println (" the searched key does not exist! ");} If (Map. containsvalue (" www.mldn.cn ") {// determines whether the value exists in system. Out. println (" the searched value exists! ");} Else {system. Out. println (" the searched value does not exist! ");}}}

Output:
The search key exists!
The searched value exists!

If you want to output all the keys, use the following method:
Set <k> keyset ()

import java.util.HashMap;import java.util.Map;import java.util.Iterator;import java.util.Set;public class HashMapDemo03{    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<String> keys = map.keySet();        Iterator<String> iter = keys.iterator();        while(iter.hasNext()){            String str = iter.next();            System.out.print(str+"、");        }    }}

Output:

Zhinangtuan, mldn, mldnjava,

Since all the keys can be output, all the values can be output.
Collection <v> values ()

import java.util.HashMap;import java.util.Map;import java.util.Iterator;import java.util.Collection;public class HashMapDemo04{    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");        Collection<String> keys = map.values();        Iterator<String> iter = keys.iterator();        while(iter.hasNext()){            String str = iter.next();            System.out.print(str+"、");        }    }}

Output: www.zhinangtuan.cn, www.mldn.cn, www.mldnjava.cn,

There is also a hashtable subclass in map. In fact, the launch time of this subclass is the same as that of vector, and both belong to the old class.

import java.util.Hashtable;import java.util.Map;import java.util.Iterator;import java.util.Set;import java.util.Collection;public class HashtableDemo01{    public static void main(String[] args){        Map<String,String> map = null;        map = new Hashtable<String,String>();        map.put("mldn","www.mldn.cn");        map.put("zhinangtuan","www.zhinangtuan.cn");        map.put("mldnjava","www.mldnjava.cn");        Set<String> keys = map.keySet();        Iterator<String> iter = keys.iterator();        while(iter.hasNext()){            String str = iter.next();            System.out.print(str+"、");        }        System.out.println("");        Collection<String> values = map.values();        Iterator<String> iterv = values.iterator();        while(iterv.hasNext()){            String str = iterv.next();            System.out.print(str+"、");        }    }}

Output:

Mldn, mldnjava, zhinangtuan,
Www.mldn.cn, www.mldnjava.cn, www.zhinangtuan.cn,

Differences between hashmap and hashtable
No. Comparison point hashmap hashtable
1. It was launched after jdk1.2, and belongs to the new operation class jdk1.0, and belongs to the old operation class.
2. The performance adopts asynchronous processing, and the performance is higher adopts synchronous processing, with low performance
3. thread security is a non-thread-safe operation and a thread-safe operation.

There is also a treemap subclass in map, which also belongs to the sorting class and is sorted by key.

import java.util.TreeMap;import java.util.Map;import java.util.Iterator;import java.util.Set;import java.util.Collection;public class TreeMapDemo01{    public static void main(String[] args){        Map<String,String> map = null;        map = new TreeMap<String,String>();        map.put("A、mldn","www.mldn.cn");        map.put("B、zhinangtuan","www.zhinangtuan.cn");        map.put("C、mldnjava","www.mldnjava.cn");        Set<String> keys = map.keySet();        Iterator<String> iter = keys.iterator();        while(iter.hasNext()){            String str = iter.next();            System.out.print(str+"、");        }        System.out.println("");        Collection<String> values = map.values();        Iterator<String> iterv = values.iterator();        while(iterv.hasNext()){            String str = iterv.next();            System.out.print(str+"、");        }    }}

Output:

A, mldn, B, zhinangtuan, C, mldnjava,
Www.mldn.cn, www.zhinangtuan.cn, www.mldnjava.cn,

You can use treemap to conveniently perform sorting. If the custom class is used as the key, you must implement the comparable interface and specify the comparison rules.

Weak reference: weakhashmap

The data in the map subclass described previously is saved using strong references. That is, the content in the map subclass is always retained in the collection, no matter whether it is used or not, you can use the weakhashmap class if you want to automatically clear unnecessary data from the set.

Weakhashmap is defined as follows:

Public class weakhashmap <K, V> extends abstractmap <K, V> implements Map <K, V>

If some content in a map is not used for a long time, it will not be deleted according to the previous practice. If you want it to be deleted automatically, you can use weak references.

import java.util.WeakHashMap;import java.util.Map;import java.util.Set;import java.util.Iterator;import java.util.Collection;public class WeakHashMapDemo01{    public static void main(String[] args){        Map<String,String> map = null;        map = new WeakHashMap<String,String>();        map.put(new String("mldn"),new String("www.mldn.cn"));        map.put(new String("zhinangtuan"),new String("www.zhinangtuan.cn"));        map.put(new String("mldnjava"),new String("www.mldnjava.cn"));        System.gc();        map.put(new String("lxh"),new String("lixinghua"));        System.out.println(map);    }}

Output:

{Lxh = lixinghua}

Tip: Description of object reference intensity
Beginning with JDK, Java classifies object references into four levels, so that the program can control the object lifecycle more flexibly. the four levels are from high to low: strong reference, soft reference, weak reference, and virtual reference. The following describes the differences between the following four types of references:

Strong reference: When the memory is insufficient, the JVM would rather stop the program due to an outofmemeryerror or recycle the object to release space.
Soft reference: When the memory is insufficient, the memory of these objects will be recycled to implement memory-sensitive high-speed cache.
Weak reference: no matter whether the memory is insufficient or not, it is immediately reclaimed by the garbage collector.
Virtual Reference: Same as no reference

4. Summary

1. introduced the features and basic operations of map.
2. Relationship between map and map. Entry
3. Map subclass: hashmap, hashtable, treemap, weakhashmap
4. The main function is to find the value based on the key.

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.