Array initialization

A very simple question, I think. How to initialize ArrayListwith a name time.

Thank.

+3
source share
5 answers

It depends on what you mean by initialization. To just initialize a variable timewith the value of a link to a new one ArrayList, you do

ArrayList<String> time = new ArrayList<String>();

(replace Stringwith the type of objects you want to keep in the list.)

If you want to put the material on the list, you can do

ArrayList<String> time = new ArrayList<String>();
time.add("hello");
time.add("there");
time.add("world");

You can also do

ArrayList<String> time = new ArrayList<String>(
    Arrays.asList("hello", "there", "world"));

or using an instance initializer

ArrayList<String> time = new ArrayList<String>() {{
    add("hello");
    add("there");
    add("world");
}};
+10
source

Arrays.asListallows you to build Listfrom a list of values.

ArrayList, , Arrays.asList.

ArrayList time = new ArrayList(Arrays.asList("a", "b", "c"));

List , Arrays.asList.

List time = Arrays.asList("a", "b", "c");
+2

<1.5 jdk

List time = new ArrayList();

gt or eq 1.5 jdk

List<T> time = new ArrayList<T>();
+1
source
ArrayList<String> time = ArrayList.class.newInstance();
+1
source

Alternative:

Using Google Collections, you can write:

import com.google.collect.Lists.*;

List<String> time = newArrayList();

You can even specify the initial content Listas follows:

List<String> time = newArrayList("a", "b", "c");
0
source

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


All Articles