C# => JAVA:在声明时填充静态 ArrayList。可能的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2052328/
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-10-29 19:08:17  来源:igfitidea点击:

C# => JAVA: Filling a static ArrayList on declaration. Possible?

c#javalistarraylist

提问by Peterdk

In my C# project I have a static List that gets filled immediately when declared.

在我的 C# 项目中,我有一个静态列表,在声明时会立即填充。

  private static List<String> inputs = new List<String>()
        { "Foo", "Bar", "Foo2", "Bar2"};

How would I do this in Java using the ArrayList?

我将如何使用 ArrayList 在 Java 中做到这一点?

I need to be able to access the values without creating a instance of the class. Is it possible?

我需要能够在不创建类的实例的情况下访问这些值。是否可以?

回答by Clint

You can use Double Brace Initialization. It looks like:

您可以使用双括号初始化。看起来像:

private static List<String> inputs = new ArrayList<String>()
  {{ add("Foo");
    add("Bar");
    add("Foo2");
    add("Bar2");
  }};

回答by MAK

I don't understand what you mean by

我不明白你的意思

able to access the values without creating a instance of the class

能够在不创建类的实例的情况下访问这些值

but the following snippet of code in Java has pretty much the same effect in Java as yours:

但是以下 Java 中的代码片段在 Java 中的效果与您的几乎相同:

private static List<String> inputs = Arrays.asList("Foo", "Bar", "Foo2", "Bar2");

回答by Jason Nichols

You can make static calls by enclosing them within static{} brackets like such:

您可以通过将它们括在静态{} 括号中来进行静态调用,如下所示:

private static final List<String> inputs = new ArrayList<String>();

static {
  inputs.add("Foo");
  inputs.add("Bar");
  inputs.add("Foo2");
  inputs.add("Bar2");
}

回答by jdmichal

Do you need this to be an ArrayListspecifically, or just a list?

你需要这是一个ArrayList具体的,还是只是一个列表?

Former:

前任的:

private static java.util.List<String> inputs = new java.util.ArrayList<String>(
    java.util.Arrays.<String>asList("Foo", "Bar", "Foo2", "Bar2"));

Latter:

后者:

private static java.util.List<String> inputs =
    java.util.Arrays.<String>asList("Foo", "Bar", "Foo2", "Bar2");

java.util.Arrays#asList(...) API

java.util.Arrays#asList(...) API

回答by Kevin Bourrillion

You may enjoy ImmutableListfrom Guava:

你可以ImmutableList番石榴中享受:

ImmutableList<String> inputs = ImmutableList.of("Foo", "Bar", "Foo2", "Bar2");

ImmutableList<String> inputs = ImmutableList.of("Foo", "Bar", "Foo2", "Bar2");

The first half of this youtube videodiscusses the immutable collections in great detail.

这个 youtube 视频的前半部分非常详细地讨论了不可变集合。