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

What is another way to initialize HashMap in Java

2025-03-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

How is another way to initialize HashMap in Java? aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

If you are exposed to different languages, Java is a completely "bloated, verbose" language in terms of syntax and code, and on the other hand, this bloated and verbose reflects its rigorous side, as one of the reasons for building large, complex projects.

1. The literary and artistic writing of HashMap initialization

HashMap is a commonly used data structure, which is generally used as a container for data dictionary or Hash lookup. Ordinary young people usually initialize it like this:

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

After reading this code, many people will think that it is too verbose to write this. In this regard, young people in literature and art generally come like this:

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

Well, it looks a lot more elegant, one step at a time, one step at a time. Then the question comes, some children's shoes will ask: Nani? What exactly is the meaning and usage of the double parentheses here? Haha, it's actually very simple. Take a look at the following code and you'll know what it means.

Public class Test {/ * private static HashMap map = new HashMap () {{put ("Name", "June"); put ("QQ", "2572073701");}}; * / public Test () {System.out.println ("Constructor called: constructor called") } static {System.out.println ("Static block called: static block called");} {System.out.println ("Instance initializer called: instance initialization block called");} public static void main (String [] args) {new Test (); System.out.println ("= ="); new Test ();}}

Output:

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

Note: if you don't understand the function and usage of static, please refer to:

Http://my.oschina.net/leejun2005/blog/193439#OSC_h4_1 Why is the main method public static void?

Http://my.oschina.net/leejun2005/blog/144349#OSC_h4_2 Design pattern: talk about the singleton pattern in java (Singleton)

In other words, the first bracket actually defines an anonymous inner class (Anonymous Inner Class), and the second bracket is actually an instance initialization block (instance initializer block), which is executed when the internal anonymous class is constructed. These blocks are called "instance initialization blocks" because they are defined within the scope of an instance of a class.

If the above code is written in the Test class, you will see that the Test$1.class file will be generated after compilation, and the contents of the file will be decompiled:

D:\ eclipse_indigo\ workspace_home\ CDHJobs\ bin\ pvuv\ > 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.javapackage pvuv.zhaopin;import java.util.HashMap / / Referenced classes of package pvuv.zhaopin:// Testclass Test$1 extends HashMap / / created a subclass {Test$1 () {/ / second {} of HashMap and put the code in the constructor put ("Name", "June"); put ("QQ", "2572073701") } D:\ eclipse_indigo\ workspace_home\ CDHJobs\ bin\ pvuv\ > 2, by extension

This way of writing, by extension, can be played like this when initializing ArrayList and Set, for example, you can also play like this:

List names = new ArrayList () {{for (int I = 0; I < 10; iTunes +) {add ("A" + I);}; System.out.println (names.toString ()); / / [A0, A1, A2, A3, A4, A5, A6, A7, A8, A9] 3, Java7: add support for collections

In Java 7 you can create collections like Ruby, Perl, and Python.

Note: these sets are immutable.

PS: since the author of the original text [5] did not mark which minor version of java 7 introduced these new features, for students who left messages and reported errors, please try to be greater than 1.7.00.009 or java8?

List list = new ArrayList (); list.add ("item"); String item = list.get (0); Set set = new HashSet (); set.add ("item"); Map map = new HashMap (); map.put ("key", 1); int value = map.get ("key"); / / now you can also: List list = ["item"]; String item = list [0]; Set set = {"item"} Map map = {"key": 1}; int value = map ["key"]; 4. Potential problems in literary and artistic writing

The advantages of the literary writing mentioned at the beginning of the article are obvious at a glance. Here is a list of the disadvantages of this approach, which may cause serialization failure if the object is serialized.

1. This is the declaration of an anonymous inner class, so the reference holds a reference to the external class. So at that time, when serializing this collection, the external class will also be unknowingly serialized, and when the external class does not implement the serialize interface, it will report an error.

two。 In the above example, you actually declare a subclass that inherits from HashMap. However, some serialization methods, such as serialization to json through Gson, or to serialization to xml, cannot serialize subclasses of Hashset or HashMap in the class library, resulting in serialization failure. Solution: reinitialize to a HashMap object:

New HashMap (map)

So that you can initialize normally.

5. Execution efficiency

When a new tool or writing appears, the apes will say, "how is the performance?" (the first sentence when talking to a boy about a girl is usually: "what does she look like? how much is BWH?" One truth:))

With regard to these two writing methods, my notebook here tests literary writing and ordinary writing to create 10000000 Map respectively, and the result is 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 < 1000000000; iTunes +) {HashMap map = new HashMap () {{put ("Name", "June"); put ("QQ", "2572073701") }};} System.out.println (System.currentTimeMillis ()-st); / / 1217 * / for (int I = 0; I < 1000000; iTunes +) {HashMap map = new HashMap (); map.put ("Name", "June"); map.put ("QQ", "2572073701") } System.out.println (System.currentTimeMillis ()-st); / / 1064}} 6. Some variable initialization problems associated with instance initialization blocks

From a code point of view, why can a not declare the type first? What do you think the values of a, b and c are respectively? Can you explain why?

TIPS: if you are not familiar with this mechanism, it is recommended that you try decompiling the 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-local variables:" + 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.2bytecode decompilation: / / 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.javaimport java.io.PrintStream;public class Test {Test () {this.e () {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 -\ u6210\ u5458\ u53D8\ u91CF\ uFF1A")) .append (this.h). ToString ()) System.out.println ((new StringBuilder ("h -\ u5C40\ u90E8\ u53D8\ u91CF:")) .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) .append (). 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 Output:a: 33b: 22c: 11d: 44f: 5e: 6h-member variable: 8h-local variable: 88g: 77 this is the answer to the question about another way of initializing HashMap in Java. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

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

Servers

Wechat

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

12
Report