Title: HashMap的几种初始化方法 · Issue #2 · Sitrone/LeetcodeInJava · GitHub
Open Graph Title: HashMap的几种初始化方法 · Issue #2 · Sitrone/LeetcodeInJava
X Title: HashMap的几种初始化方法 · Issue #2 · Sitrone/LeetcodeInJava
Description: ArrayList初始化方法 常规方法 List
Open Graph Description: ArrayList初始化方法 常规方法 List
X Description: ArrayList初始化方法 常规方法 List<string> list = new ArrayList</string><string>(); list.add("string1"); list.add("string2"); //some other list.add() code...... list.add...
Opengraph URL: https://github.com/Sitrone/LeetcodeInJava/issues/2
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"HashMap的几种初始化方法","articleBody":"## ArrayList初始化方法\n1. 常规方法 \n\n``` java\nList\u003cstring\u003e list = new ArrayList\u003c/string\u003e\u003cstring\u003e(); \nlist.add(\"string1\"); \nlist.add(\"string2\"); \n//some other list.add() code...... \nlist.add(\"stringN\");\n```\n1. 使用Arrrays.asList()方法 \n\n``` java\nArrayList\u003cString\u003e list = new ArrayList(Arrays.asList(\"Tom\", \"Jerry\", \"Mike\")); \n```\n1. 使用双括号\n\n``` java\nList list = new ArrayList\u003cString\u003e(){{ \n add(\"A\"); \n add(\"B\"); \n}};\n```\n## HashMap初始化\n### 非static HashMap\n1. 最简单直观的 \n\n``` java\n Map\u003cString, Integer\u003e myMap = new HashMap\u003cString, Integer\u003e();\n myMap.put(\"Li Lei\", 1);\n myMap.put(\"Han Meimei\", 2);\n```\n\n但是初始化数据多的时候,这样写会很麻烦,有没有更好的办法呢? \n1. 双括号,匿名内部类初始化HashMap \n\n``` java\n Map\u003cString, Integer\u003e myMap = new HashMap\u003cString, Integer\u003e() {\n {\n put(\"key1\",\"value1\");\n put(\"key2\",\"value2\");\n }\n };\n```\n### 初始化immutable HashMap\n1. 同上 \n2. 双括号 \n\n``` java\npublic static final HashMap hm = new HashMap(){\n{\n put(\"key1\",\"value1\");\n put(\"key2\",\"value2\");\n}\n}; \n```\n\n上面的代码包含了两个隐藏的东西:\n \\* 一个匿名内部类\n \\* 一个实例块 \n\n可以对上面的代码进行拆解\n- 拆除匿名内部类 \n\n``` java\nprivate static class MyHashMap() extends HashMap\n{\n {\n put(\"key1\",\"value1\");\n put(\"key2\",\"value2\");\n }\n}\npublic static final HashMap hm = new MyHashMap();\n```\n- 拆除代码块\n\n``` java\nprivate static class MyHashMap() extends HashMap\n{\n public MyHashMap()\n {\n this.put(\"key1\",\"value1\"); // \u003c-- added 'this'\n this.put(\"key2\",\"value2\"); // \u003c-- added 'this'\n }\n}\npublic static final HashMap hm = new MyHashMap(); \n```\n#### immutable HashMap初始化推荐的方法:\n\n``` java\npublic class Test {\n private static final Map\u003cInteger, String\u003e MY_MAP = createMap();\n\n private static Map\u003cInteger, String\u003e createMap() {\n Map\u003cInteger, String\u003e result = new HashMap\u003cInteger, String\u003e();\n result.put(1, \"one\");\n result.put(2, \"two\");\n return Collections.unmodifiableMap(result);\n }\n}\n```\n\n或者是用Google提供的[Guava](https://github.com/google/guava) \n\n``` java\nstatic final Map\u003cInteger, String\u003e MY_MAP = ImmutableMap.of(\n 1, \"one\",\n 2, \"two\"\n);\n```\n\n---\n\n**双括号的方式不推荐使用** \n原因是:\n1. 匿名内部类的声明方式,所以引用中持有着外部类的引用。所以当时串行化这个集合时外部类也会被不知不觉的串行化,当外部类没有实现serialize接口时,就会报错。 \n2. 这种方式其实是声明了一个继承自HashMap的子类。然而有些串行化方法,例如要通过Gson串行化为json,或者要串行化为xml时,类库中提供的方式,是无法串行化Hashset或者HashMap的子类的,从而导致串行化失败。 \n#### 参考链接\n\n**使用双括号初始化可能出现的问题** \n1. http://www.c2.com/cgi/wiki?DoubleBraceInitialization\n2. http://stackoverflow.com/questions/6802483/how-to-directly-initialize-a-hashmap-in-a-literal-way \n\n**具体的例子** \n1. [HashMap Construction with initial values](https://coderanch.com/t/386333/java/java/HashMap-Construction-initial-values)\n2. [聊聊 Java 中 HashMap 初始化的另一种方式](https://my.oschina.net/leejun2005/blog/282783) \n3. [Java的大括号语法糖](https://my.oschina.net/trydofor/blog/79222)\n","author":{"url":"https://github.com/Sitrone","@type":"Person","name":"Sitrone"},"datePublished":"2016-09-22T11:36:42.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":0},"url":"https://github.com/2/LeetcodeInJava/issues/2"}
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:1d10619b-56d3-cd1e-4f8a-374f921429cd |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | E9B2:C0A64:75B050:9F242A:6A6006A2 |
| html-safe-nonce | cb32b561726396b38b5d736e28a07aa850e30abb234a8e04a33172d257b93bcd |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFOUIyOkMwQTY0Ojc1QjA1MDo5RjI0MkE6NkE2MDA2QTIiLCJ2aXNpdG9yX2lkIjoiMzIyMDY2OTk3NTU5OTUxNTI5OCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 8d6999e2c9d2852a441d77a67c8edfa248079ac98eb75bcf5c7ed59e6def1f22 |
| hovercard-subject-tag | issue:178586357 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/Sitrone/LeetcodeInJava/2/issue_layout |
| twitter:image | https://opengraph.githubassets.com/4b3a80a933b0f8708bf663a19c791b367010cdcd52727367a156fb5aefbceeb2/Sitrone/LeetcodeInJava/issues/2 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/4b3a80a933b0f8708bf663a19c791b367010cdcd52727367a156fb5aefbceeb2/Sitrone/LeetcodeInJava/issues/2 |
| og:image:alt | ArrayList初始化方法 常规方法 List |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | Sitrone |
| hostname | github.com |
| expected-hostname | github.com |
| None | 5789899e92b20db289de946d86eb20bf5c9626276695d68f58a8c47cdda699b7 |
| turbo-cache-control | no-preview |
| go-import | github.com/Sitrone/LeetcodeInJava git https://github.com/Sitrone/LeetcodeInJava.git |
| octolytics-dimension-user_id | 5569320 |
| octolytics-dimension-user_login | Sitrone |
| octolytics-dimension-repository_id | 61412709 |
| octolytics-dimension-repository_nwo | Sitrone/LeetcodeInJava |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 61412709 |
| octolytics-dimension-repository_network_root_nwo | Sitrone/LeetcodeInJava |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 6ddc048ddf80664b9b33547b619db10313c482f1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width