納悶Java為什麼不直接在語言層級支援這個功能
List<String> nameLt = ["Justin", "Monica"];
Map<String, Integer> scoreMap = {
"Justin": 95,
"Monica": 100
};
之前有相關 JEP:
不在語法層級支援的原因可能是這一段吧:
In the past, there have been a few proposals floated to change the Java programming language to support collection literals. However, as is often the case with language features, no feature is as simple or as clean as one might first imagine, and so collection literals will not be appearing in the next version of Java.
之前 Sun 某個 Java 傳教士就曾在某個研討會投影片中靠北過了,反正他的大意就是「你們這些人總是覺得演化 Java 時這好哪好,其實才沒你們想的這麼簡單,我們要考慮的情況可多著嘞」…XD
但大概能理解,能用現存語法解決的地方,實在沒必要加個新的語法定義,除非真的效益差太多了。
Much of the benefit of collection literals can be gained by providing library APIs for creating small collection instances, at significantly reduced cost and risk compared to changing the language. For example, the code to create a small Set instance might look like this:
可以理解用library完成就不用改語法。但是 java9 的版本還是不太好用啊。
補充一個java9 對map比較好用的版本
import static java.util.Map.entry;
Map<Integer,String> map = Map.ofEntries(
entry(1, "a"),
entry(2, "b"),
entry(3, "c"),
...
entry(26, "z"));
但是多層下還是醜醜的..XD
API 已經提供到 10 個 pair 的 of() overload 了,這還不夠嗎?
會放 10 個 pair 以上的 map literal ? 我覺得程式要 refactor 了