Java ArrayList and HashMap on

Can someone please provide an example of creating a Java ArrayList and HashMap on the fly? So instead of doing an add() or put() , actually supplying the seed data for the array/hash at the class instantiation?

To provide an example, something similar to PHP for instance:

$array = array (3, 1, 2);
$assoc_array = array( 'key' => 'value' );

List<String> list = new ArrayList<String>() {
 {
    add("value1");
    add("value2");
 }
};

Map<String,String> map = new HashMap<String,String>() {
 {
    put("key1", "value1");
    put("key2", "value2");
 }
};

一个很好的方法是使用Google Collections:

List<String> list = ImmutableList.of("A", "B", "C");

Map<Integer, String> map = ImmutableMap.of(
  1, "A",
  2, "B",
  3, "C");

Arrays can be converted to List s:

List<String> al = Arrays.asList("vote", "for", "me"); //pandering

Note that this does not return an ArrayList but an arbitrary List instance (in this case it's an Array.ArrayList )!

Bruno's approach works best and could be considered on the fly for maps. I prefer the other method for lists though (seen above):

Map<String,String> map = new HashMap<String,String>() {
 {
    put("key1", "value1");
    put("key2", "value2");
 }
};
链接地址: http://www.djcxy.com/p/82404.html

上一篇: java:打印当前回溯

下一篇: Java ArrayList和HashMap在上