Examples illustrate the initialization and traversal of a HashMap in Java programming

  • 2020-04-01 04:18:30
  • OfStack

I. initialization of HashMap
1. Literary notation of HashMap initialization
    HashMap is a common data structure used as a container for data dictionaries or Hash lookups. The average young person initializes:

 


HashMap<String, String> map =
  new HashMap<String, String>();
 map.put("Name", "June"); 
 map.put("QQ", "2572073701");

After reading this piece of code, many people will feel that it is too verbose, for which, literary and artistic young people generally like this:
 


HashMap<String, String> map =
  new HashMap<String, String>() {
 {
 put("Name", "June"); 
 put("QQ", "2572073701"); 
 }
 };

    Well, it looks a lot more elegant, one step in place, a one-piece. And then there's the question: nani? What does this double bracket mean, and how does it work? Haha, it's actually very simple, just look at the code below to see what it means.


public class Test {
 
 public Test() {
  System.out.println("Constructor called : the constructor is called ");
 }
 static {
  System.out.println("Static block called : the static block is called ");
 }
 {
  System.out.println("Instance initializer called : the instance initialization block is called ");
 }
 public static void main(String[] args) {
  new Test();
  System.out.println("=======================");
  new Test();
 }
}

Output:


 Static block called : the static block is called 
 Instance initializer called : instance initialization is called 
 Constructor called : the constructor is called 
 =======================
 Instance initializer called : instance initialization is called 
 Constructor called : the constructor is called 

That is, the first bracket actually defines an Anonymous Inner Class, and the second bracket is actually an instance initializer block, which is executed when the Inner Anonymous Class is constructed. The blocks are called "instance initializer blocks" because they are defined within the instance scope of a class.
If the above code is written in the Test class, after compiling, you will see that the Test$1.class file will be generated and the file contents will be decompiled:


D:eclipse_indigoworkspace_homeCDHJobsbinpvuv>jad -p Test$1.class

// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: Test.java


package pvuv.zhaopin;
import java.util.HashMap;
// Referenced classes of package pvuv.zhaopin:
// Test
 class Test$1 extends HashMap //A subclass of HashMap is created
 {
 Test$1()
 { //The code in the second {} goes into the constructor
 put("Name", "June");
 put("QQ", "2572073701");
 }
 }


D:eclipse_indigoworkspace_homeCDHJobsbinpvuv>

2. Generalize
  This, by extension, can be used to initialize ArrayList and Set, for example, you can also play:


 List<String> names = new ArrayList<String>() {
 {
 for (int i = 0; i < 10; i++) {
  add("A" + i);
 }
 }
 };
 System.out.println(names.toString()); // [A0, A1, A2, A3, A4, A5, A6, A7, A8, A9]

3. Java7: added support for collections
In Java 7 you can now create collections like Ruby, Perl, and Python.
Note: these sets are immutable.

PS: since the author did not indicate which small version number of Java 7 introduced these new features, please try greater than 1.7.0_09 or java8 for those of you who made an error in your comments.


List list = new ArrayList();
 list.add("item");
 String item = list.get(0);
 Set< String> set = new HashSet< String>();
 set.add("item");
 Map< String, Integer> map = new HashMap< String, Integer>();
 map.put("key", 1);
 int value = map.get("key");
 //Now you can also:
 List< String> list = ["item"];
 String item = list[0];
 
 Set< String> set = {"item"};
 
 Map< String, Integer> map = {"key" : 1};
 int value = map["key"];

4. Potential problems of literary writing
      The advantages of literary writing mentioned at the beginning of the article are obvious. Here is a list of the disadvantages of this method. If the object is serialized, serialization may fail.
  1. This is the declaration of anonymous inner classes, so references to external classes are held in the reference. So when serializing this collection, the external class will be serialized unconsciously, and when the external class does not implement the serialize interface, it will report an error.

2. In the example above, you actually declared a subclass inherited from HashMap. However, some serialization methods, such as serialization to json via Gson or serialization to XML, are provided in the class library in such a way that a Hashset or a subclass of HashMap cannot be serialized, resulting in a serialization failure. Solution: reinitialize to a HashMap object:


new HashMap(map);

So you can initialize it normally.

5. Execution efficiency
    When a new tool or writing method appeared, apes would say: how is the performance? The first thing a guy says about a girl is, "what do you look like? How many measurements?" One lesson :))
As for the two ways of writing, the test results of literary writing and ordinary writing on my notebook to create 10,000,000 maps are 1217 and 1064, with a difference of 13%.


public class Test {
 public static void main(String[] args) {
  long st = System.currentTimeMillis();
  /*
  for (int i = 0; i < 10000000; i++) {
   HashMap< String, String> map = new HashMap< String, String>() {
    {
     put("Name", "June");
     put("QQ", "2572073701");
    }
   };
  }
  System.out.println(System.currentTimeMillis() - st); // 1217
  */
  for (int i = 0; i < 10000000; i++) {
   HashMap< String, String> map = new HashMap< String, String>();
   map.put("Name", "June");
   map.put("QQ", "2572073701");
  }
  System.out.println(System.currentTimeMillis() - st); // 1064
 }
}

6. Some variable initialization problems associated with the instance initialization block
  From the code point of view, why can a not declare the type first? What do you think the values of a, b and c are? Can you explain why?
TIPS: if you're not familiar with this mechanism, try decomcompiling a bytecode file.

6.1 test source code


public class Test {
 
 int e = 6;
 Test() {
  int c = 1;
  this.f = 5;
  int e = 66;
 }
 int f = 55;
 int c = 11;
 int b = 1;
 {
  a = 3;
  b = 22;
 }
 int a = 33;
 static {
  d = 4;
 }
 static int d = 44;
 
 int g = 7;
 int h = 8;
 public int test(){
  g = 77;
  int h = 88;
  System.out.println("h -  Member variables: " + this.h);
  System.out.println("h -  A local variable : " + h);
  return g;
 }
 public static void main(String[] args) {
  System.out.println("a: " + new Test().a);
  System.out.println("b: " + new Test().b);
  System.out.println("c: " + new Test().c);
  System.out.println("d: " + new Test().d);
  System.out.println("f: " + new Test().f);
  System.out.println("e: " + new Test().e);
  System.out.println("g: " + new Test().test());
 }
}

6.2 byte code decompiling:


// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: Test.java
import java.io.PrintStream;
public class Test
{
 Test()
 {
  this.e = 6;
  f = 55;
  this.c = 11;
  b = 1;
  a = 3;
  b = 22;
  a = 33;
  g = 7;
  h = 8;
  int c = 1;
  f = 5;
  int e = 66;
 }
 public int test()
 {
  g = 77;
  int h = 88;
  System.out.println((new StringBuilder("h - u6210u5458u53D8u91CFuFF1A")).append(this.h).toString());
  System.out.println((new StringBuilder("h - u5C40u90E8u53D8u91CF: ")).append(h).toString());
  return g;
 }
 public static void main(String args[])
 {
  System.out.println((new StringBuilder("a: ")).append((new Test()).a).toString());
  System.out.println((new StringBuilder("b: ")).append((new Test()).b).toString());
  System.out.println((new StringBuilder("c: ")).append((new Test()).c).toString());
  new Test();
  System.out.println((new StringBuilder("d: ")).append(d).toString());
  System.out.println((new StringBuilder("f: ")).append((new Test()).f).toString());
  System.out.println((new StringBuilder("e: ")).append((new Test()).e).toString());
  System.out.println((new StringBuilder("g: ")).append((new Test()).test()).toString());
 }
 int e;
 int f;
 int c;
 int b;
 int a;
 static int d = 4;
 int g;
 int h;
 static
 {
  d = 44;
 }
}
6.3 output : 
 a: 33
 b: 22
 c: 11
 d: 44
 f: 5
 e: 6
 h -  Member variables: 8
 h -  A local variable : 88
 g: 77


An example of a HashMap traversal method
The first:


Map map = new HashMap();
  Iterator iter = map.entrySet().iterator();
  while (iter.hasNext()) {
  Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey();
  Object val = entry.getValue();
  }

High efficiency, must use this way in the future!
The second:


 Map map = new HashMap();
  Iterator iter = map.keySet().iterator();
  while (iter.hasNext()) {
  Object key = iter.next();
  Object val = map.get(key);
  }

Low efficiency, use as little as possible later!
There are two common methods for traversing HashMap, namely, using keyset and entryset to traverse, but the traversal speed of the two is different. Here is an example:


 public class HashMapTest {
  public static void main(String[] args) ...{
  HashMap hashmap = new HashMap();
  for (int i = 0; i < 1000; i ) ...{
  hashmap.put("" i, "thanks");
  }
  long bs = Calendar.getInstance().getTimeInMillis();
  Iterator iterator = hashmap.keySet().iterator();
  while (iterator.hasNext()) ...{
  System.out.print(hashmap.get(iterator.next()));
  }
  System.out.println();
  System.out.println(Calendar.getInstance().getTimeInMillis() - bs);
  listHashMap();
  }
  public static void listHashMap() ...{
  java.util.HashMap hashmap = new java.util.HashMap();
  for (int i = 0; i < 1000; i ) ...{
  hashmap.put("" i, "thanks");
  }
  long bs = Calendar.getInstance().getTimeInMillis();
  java.util.Iterator it = hashmap.entrySet().iterator();
  while (it.hasNext()) ...{
  java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
  //Entry. GetKey () returns the key corresponding to this entry
  //Entry. GetValue () returns the value corresponding to this entry
  System.out.print(entry.getValue());
  }
  System.out.println();
  System.out.println(Calendar.getInstance().getTimeInMillis() - bs);
  }
  }

The keySet is iterated twice, once to iterator, and once to the value of the key from the hashmap. Entryset is just going through the first time. It puts the key and value into the entry, so it's almost there.
Note: the traversal method of Hashtable is similar to the above!


Related articles: