Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use LinkedHashMap of JDK

2025-03-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to use LinkedHashMap of JDK". In daily operation, I believe many people have doubts about how to use LinkedHashMap of JDK. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use LinkedHashMap of JDK". Next, please follow the editor to study!

Package org.corey.demo

Import java.util.HashMap

Import java.util.Iterator

Import java.util.LinkedHashMap

Import java.util.Map

Public class Test {

/ * *

* @ param args

, /

Public static void main (String [] args) {

Map map = new LinkedHashMap (4)

Map.put ("1", "corey")

Map.put ("2", "syna")

Map.put ("3", "bobo")

Iterator it=map.keySet () .iterator ()

System.out.println ("- linked hash map--")

While (it.hasNext ()) {

String key= (String) it.next ()

System.out.println (key+ ":" + map.get (key))

}

Map map2 = new HashMap (4)

Map2.put ("1", "corey")

Map2.put ("2", "syna")

Map2.put ("3", "bobo")

Iterator it2=map2.keySet () .iterator ()

System.out.println ("- hash map--")

While (it2.hasNext ()) {

String key= (String) it2.next ()

System.out.println (key+ ":" + map2.get (key))

}

}

}

Console:

-linked hash map--

1:corey

2:syna

3:bobo

-hash map--

2:syna

1:corey

3:bobo

Thus it can be seen that our problem has been solved.

Now let's analyze its implementation principle in detail from within the LinkEdHashMap code.

Private transient Entry header

There is an attribute of Entry in LinkedHashMap; note that this Entry is not the one-way Entry we saw in HashMap last time, it has been expanded:

Private static class Entry extends HashMap.Entry {

/ / he has two pointers to the Entry of before and after, respectively

/ / Please be careful not to confuse next with them. The use of next is the same as that of HashMap.

Entry before, after

Entry (int hash, K key, V value, HashMap.Entry next) {

Super (hash, key, value, next)

}

Private void remove () {

Before.after = after

After.before = before

}

/ / insert a node in front of the current node

Private void addBefore (Entry existingEntry) {

After = existingEntry

Before = existingEntry.before

Before.after = this

After.before = this

}

Void recordAccess (HashMap m) {

LinkedHashMap lm = (LinkedHashMap) m

If (lm.accessOrder) {

Lm.modCount++

Remove ()

AddBefore (lm.header)

}

}

Void recordRemoval (HashMap m) {

Remove ()

}

}

Because LinkedHashMap is an inherited HashMap, their operations of adding, deleting and modifying are basically the same, but they use the template pattern to have a different implementation.

Let's take a look at the put method

Here is the put method of HashMap:

Public V put (K key, V value) {

If (key = = null)

Return putForNullKey (value)

Int hash = hash (key.hashCode ())

Int I = indexFor (hash, table.length)

For (Entry e = table [I]; e! = null; e = e.next) {

Object k

If (e.hash = = hash & & ((k = e.key) = = key | | key.equals (k) {

V oldValue = e.value

E.value = value

E.recordAccess (this)

Return oldValue

}

}

ModCount++

AddEntry (hash, key, value, I)

Return null

}

Void addEntry (int hash, K key, V value, int bucketIndex) {

Entry e = table [bucketIndex]

Table [bucketIndex] = new Entry (hash, key, value, e)

If (size++ > = threshold)

Resize (2 * table.length)

}

As we have analyzed in detail in the previous section, the method that is overloaded in LinkedHashMap is addEntry

Void addEntry (int hash, K key, V value, int bucketIndex) {

CreateEntry (hash, key, value, bucketIndex)

Entry eldest = header.after

If (removeEldestEntry (eldest)) {

RemoveEntryForKey (eldest.key)

} else {

If (size > = threshold)

Resize (2 * table.length)

}

}

Void createEntry (int hash, K key, V value, int bucketIndex) {

/ / as before, the linked list branch of the table sequence is manipulated first

HashMap.Entry old = table [bucketIndex]

Entry e = new Entry (hash, key, value, old)

Table [bucketIndex] = e

/ / the key lies in what is done in this step; we know that he inserted Entry before header

E.addBefore (header)

Size++

}

The Header element is initialized during construction. Remember, this method is passed down by HashMap using the template pattern in the constructor.

Void init () {

Header = new Entry (- 1, null, null, null)

Header.before = header.after = header

}

In the beginning, Header points to itself from beginning to end.

The second step is to be e.addBefore (header)

Private void addBefore (Entry existingEntry) {

After = existingEntry

Before = existingEntry.before

Before.after = this

After.before = this

}

If you re-put, then it is:

Let's take a look at how he got his keySet:

Overloaded the method of newKeyIterator ():

Iterator newKeyIterator () {return newKeyIterator ();}

Let's take a look at how iterators are implemented:

Private abstract class LinkedHashIterator implements Iterator {

/ / from the beginning of figure 3, we can see that the node added for the first time is located in the location of header.after.

Entry nextEntry = header.after

Entry lastReturned = null

Int expectedModCount = modCount

/ / nextnEntry is not the end if it is not header.

Public boolean hasNext () {

Return nextEntry! = header

}

Public void remove () {

If (lastReturned = = null)

Throw new IllegalStateException ()

If (modCount! = expectedModCount)

Throw new ConcurrentModificationException ()

LinkedHashMap.this.remove (lastReturned.key)

LastReturned = null

ExpectedModCount = modCount

}

Entry nextEntry () {

If (modCount! = expectedModCount)

Throw new ConcurrentModificationException ()

If (nextEntry = = header)

Throw new NoSuchElementException ()

/ / the pointer goes down along after

Entry e = lastReturned = nextEntry

/ / move nextEntry to the next bit in advance

NextEntry = e.after

Return e

}

}

The next method is abstracted because the iterative order of values and keySet is the same, but the values returned are different, so you can set the

The traversal mode of Entry is pushed to the upper level, while values and keys are left to the subclass implementation respectively.

Private class KeyIterator extends LinkedHashIterator {

Public K next () {return nextEntry () .getKey ();

}

Private class KeyIterator extends LinkedHashIterator {

Public K next () {return nextEntry () .getKey ();

}

Private class ValueIterator extends LinkedHashIterator {

Public V next () {return nextEntry () .value;}

}

Private class EntryIterator extends LinkedHashIterator {

Public Map.Entry next () {return nextEntry ();}

}

At this point, the study on "how to use the LinkedHashMap of JDK" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report