We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
List<string> list = new ArrayList</string><string>(); list.add("string1"); list.add("string2"); //some other list.add() code...... list.add("stringN");
ArrayList<String> list = new ArrayList(Arrays.asList("Tom", "Jerry", "Mike"));
List list = new ArrayList<String>(){{ add("A"); add("B"); }};
Map<String, Integer> myMap = new HashMap<String, Integer>(); myMap.put("Li Lei", 1); myMap.put("Han Meimei", 2);
但是初始化数据多的时候,这样写会很麻烦,有没有更好的办法呢?
Map<String, Integer> myMap = new HashMap<String, Integer>() { { put("key1","value1"); put("key2","value2"); } };
public static final HashMap hm = new HashMap(){ { put("key1","value1"); put("key2","value2"); } };
上面的代码包含了两个隐藏的东西: * 一个匿名内部类 * 一个实例块
可以对上面的代码进行拆解
private static class MyHashMap() extends HashMap { { put("key1","value1"); put("key2","value2"); } } public static final HashMap hm = new MyHashMap();
private static class MyHashMap() extends HashMap { public MyHashMap() { this.put("key1","value1"); // <-- added 'this' this.put("key2","value2"); // <-- added 'this' } } public static final HashMap hm = new MyHashMap();
public class Test { private static final Map<Integer, String> MY_MAP = createMap(); private static Map<Integer, String> createMap() { Map<Integer, String> result = new HashMap<Integer, String>(); result.put(1, "one"); result.put(2, "two"); return Collections.unmodifiableMap(result); } }
或者是用Google提供的Guava
static final Map<Integer, String> MY_MAP = ImmutableMap.of( 1, "one", 2, "two" );
双括号的方式不推荐使用 原因是:
使用双括号初始化可能出现的问题
具体的例子
The text was updated successfully, but these errors were encountered:
No branches or pull requests
ArrayList初始化方法
HashMap初始化
非static HashMap
但是初始化数据多的时候,这样写会很麻烦,有没有更好的办法呢?
初始化immutable HashMap
上面的代码包含了两个隐藏的东西:
* 一个匿名内部类
* 一个实例块
可以对上面的代码进行拆解
immutable HashMap初始化推荐的方法:
或者是用Google提供的Guava
双括号的方式不推荐使用
原因是:
参考链接
使用双括号初始化可能出现的问题
具体的例子
The text was updated successfully, but these errors were encountered: