Java ArrayList 和 HashMap 动态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/852822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:12:14  来源:igfitidea点击:

Java ArrayList and HashMap on-the-fly

javacollections

提问by Steve M

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

可有人请提供创建一个Java的例子ArrayListHashMap上飞?因此,不是执行add()or put(),而是在类实例化时实际为数组/散列提供种子数据?

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

举个例子,例如类似于 PHP 的东西:

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

采纳答案by bruno conde

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

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

回答by Jon Skeet

You mean like this?

你的意思是这样?

public List<String> buildList(String first, String second)
{
     List<String> ret = new ArrayList<String>();
     ret.add(first);
     ret.add(second);
     return ret;
}

...

List<String> names = buildList("Jon", "Marc");

Or are you interested in the ArrayListconstructor which takes a Collection<? extends E>? For example:

或者您对ArrayList采用 a的构造函数感兴趣Collection<? extends E>吗?例如:

String[] items = new String[] { "First", "Second", "Third" };
// Here's one way of creating a List...
Collection<String> itemCollection = Arrays.asList(items);
// And here's another
ArrayList<String> itemList = new ArrayList<String>(itemCollection);

回答by Steve McLeod

A nice way of doing this is using Google Collections:

这样做的一个好方法是使用Google Collections

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

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

回答by cgp

Arrays can be converted to Lists:

数组可以转换为Lists:

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

Note that this does notreturn an ArrayListbut an arbitrary Listinstance (in this case it's an Array.ArrayList)!

请注意,这并没有返回ArrayList指任意的List情况下(在这种情况下,它是一个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");
 }
};

回答by Yuval Adam

Use a nice anonymous initializer:

使用一个不错的匿名初始化程序:

List<String> list = new ArrayList<String>() {{
    add("a");
    add("b");
}};

Same goes for a Map:

地图也是如此:

Map<String, String> map = new HashMap<String, String>() {{
    put("a", "a");
    put("b", "b");
}};

I find this the most elegant and readable.

我觉得这是最优雅和可读的。

Other methods demand creating an array first, then converting it to a List - too expensive in my taste, and less readable.

其他方法需要先创建一个数组,然后将其转换为一个 List - 在我看来太昂贵了,而且可读性较差。

回答by Andreas Petersson

for short lists:

对于短名单:

    List<String> ab = Arrays.asList("a","b");

回答by R. Oosterholt

For lists you can use Arrays.asListlike this:

对于列表,您可以像这样使用Arrays.asList

List<String> stringList = Arrays.asList("one", "two");
List<Integer> intList = Arrays.asList(1, 2);

For Maps you could use this:

对于地图,您可以使用它:

public static <K, V> Map<K, V> mapOf(Object... keyValues) {
    Map<K, V> map = new HashMap<>();

    K key = null;
    for (int index = 0; index < keyValues.length; index++) {
        if (index % 2 == 0) {
            key = (K)keyValues[index];
        }
        else {
            map.put(key, (V)keyValues[index]);
        }
    }

    return map;
}

Map<Integer, String> map1 = mapOf(1, "value1", 2, "value2");
Map<String, String> map2 = mapOf("key1", "value1", "key2", "value2");

Note: in Java 9you can use Map.of
Note2: Double Brace Initializationfor creating HashMaps as suggested in other answers has it caveats

注意:在Java 9您可以使用Map.of
Note2:Double Brace Initialization按照其他答案中的建议创建 HashMap 时,请注意