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

In my C # project, I have a static list that populates right after the declaration.

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

How do I do this in Java using an ArrayList?

I need to have access to the values ​​without instantiating the class. Is it possible?

+3
source share
5 answers

I do not understand what you mean by

the ability to access values ​​without instantiating a class

but the following piece of code in Java has almost the same effect in Java as yours:

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

You can use Double Brace Initialization . It looks like this:

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

, {}:

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

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

Do you need it to be like ArrayListor just a list?

Former:

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

last:

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

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

+5
source

You can enjoy ImmutableListfrom Guava :

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

In the first half, this youtube video discusses in detail immutable collections.

+3
source

Source: https://habr.com/ru/post/1728223/


All Articles