Inicjalizacja tablicy w jednej linii
Chciałem stworzyć listę opcji do celów testowych. Na początku zrobiłem to:
ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
Następnie przeformułowałem kod w następujący sposób:
ArrayList<String> places = new ArrayList<String>(
Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Czy jest na to lepszy sposób? 30 answers
Właściwie, prawdopodobnie "najlepszym" sposobem inicjalizacji ArrayList
jest metoda, którą napisałeś, ponieważ nie trzeba tworzyć nowego List
w żaden sposób:
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
Haczyk polega na tym, że aby odnieść się do tej instancji list
, trzeba dość dużo pisać.
Istnieją alternatywy, takie jak tworzenie anonimowej klasy wewnętrznej z inicjalizatorem instancji (znanej również jako inicjalizacja podwójnego nawiasu klamrowego):
ArrayList<String> list = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
Jednak nie przepadam za tą metodą, ponieważ to, z czym się kończy jest podklasą ArrayList
, która ma inicjalizator instancji, a ta klasa jest tworzona tylko po to, aby utworzyć jeden obiekt -- to wydaje mi się trochę przesadą.
Byłoby miło, gdyby propozycja literałów kolekcji dla Project Coin została zaakceptowana (miała zostać wprowadzona w Javie 7, ale prawdopodobnie nie będzie częścią Javy 8.):
List<String> list = ["A", "B", "C"];
Niestety nie pomoże Ci tutaj, ponieważ zainicjuje niezmienny List
, a nie an ArrayList
, a ponadto, nie jest jeszcze dostępna, jeśli kiedykolwiek będzie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-13 15:27:35
Byłoby prościej, gdybyś po prostu zadeklarował to jako List
- czy to musi być ArrayList?
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
Lub jeśli masz tylko jeden element:
List<String> places = Collections.singletonList("Buenos Aires");
Oznaczałoby to, że places
jest niezmienne (próba zmiany spowoduje wyrzucenie wyjątku UnsupportedOperationException
).
Aby utworzyć listę zmienną, która jest konkretną ArrayList
, możesz utworzyć ArrayList
z listy niezmiennej:
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-16 21:38:30
Prosta odpowiedź
W Java 9 lub później, po List.of()
dodano:
List<String> strings = List.of("foo", "bar", "baz");
Za pomocą Java 10 lub później, można to skrócić za pomocą słowa kluczowego var
.
var strings = List.of("foo", "bar", "baz");
To da ci niezmienny List
, więc nie można go zmienić.
Co jest tym, czego chcesz w większości przypadków, gdy jesteś prepopulując go.
Java 8 lub wcześniejsza:
List<String> strings = Arrays.asList("foo", "bar", "baz");
To da List
wspierane przez tablicę, więc nie może się zmienić długość.
Ale możesz zadzwonić List.set
, więc nadal jest zmienny .
Możesz zrobić Arrays.asList
jeszcze krótszy z importem statycznym:
List<String> strings = asList("foo", "bar", "baz");
Import statyczny:
import static java.util.Arrays.asList;
Które każde nowoczesne IDE zaproponuje i automatycznie zrobi dla Ciebie.
Na przykład w IntelliJ IDEA naciskamy Alt+Enter
i wybieramy Static import method...
.
Nie polecam jednak skracania metody List.of
do of
, ponieważ staje się to mylące.List.of
jest już wystarczająco krótki i dobrze się czyta.
Za pomocą Stream
s
Dlaczego to musi być List
?
W Javie 8 lub nowszej można użyć Stream
, który jest bardziej elastyczny:
Stream<String> strings = Stream.of("foo", "bar", "baz");
Możesz konkatenować Stream
s:
Stream<String> strings = Stream.concat(Stream.of("foo", "bar"),
Stream.of("baz", "qux"));
Lub możesz przejść z Stream
do List
:
import static java.util.stream.Collectors.toList;
List<String> strings = Stream.of("foo", "bar", "baz").collect(toList());
Ale najlepiej, po prostu użyj Stream
bez zbierania go do List
.
Jeśli naprawdę szczególnie potrzebujesz java.util.ArrayList
(prawdopodobnie nie.)
Cytat JEP 269 (podkreślenie moje):
Istnieje mały zestaw przypadków użycia do inicjalizacji mutowalnej instancji kolekcji z predefiniowanym zestawem wartości. Zwykle lepiej jest, aby te predefiniowane wartości znajdowały się w niezmiennej kolekcji, a następnie zainicjować zmienną kolekcję za pomocą konstruktora kopiującego.
Jeśli chcesz zarówno przygotować ArrayList
i dodać do niego później (dlaczego?), użycie
ArrayList<String> strings = new ArrayList<>(List.of("foo", "bar"));
strings.add("baz");
Lub w Javie 8 lub wcześniej:
ArrayList<String> strings = new ArrayList<>(asList("foo", "bar"));
strings.add("baz");
Lub używając Stream
:
import static java.util.stream.Collectors.toCollection;
ArrayList<String> strings = Stream.of("foo", "bar")
.collect(toCollection(ArrayList::new));
strings.add("baz");
Ale ponownie, lepiej użyć Stream
bezpośrednio zamiast zbierać go do List
.
Program do interfejsów, nie do implementacji
Powiedziałeś, że zadeklarowałeś listę jako ArrayList
w swoim kodzie, ale powinieneś to zrobić tylko wtedy, gdy używasz jakiegoś członka ArrayList
, którego nie ma w List
.
Którego najprawdopodobniej nie zrobisz.
Zazwyczaj należy zadeklarować zmienne przez najbardziej ogólny interfejs, z którego będziesz korzystać (np. Iterable
, Collection
, lub List
), i inicjalizować je za pomocą określonej implementacji (np. ArrayList
, LinkedList
lub Arrays.asList()
).
W Przeciwnym Razie ograniczysz swój kod do tego konkretnego typu, A trudniej będzie go zmienić, kiedy zechcesz.
Na przykład, jeśli przekazujesz ArrayList
do void method(...)
:
// Iterable if you just need iteration, for (String s : strings):
void method(Iterable<String> strings) {
for (String s : strings) { ... }
}
// Collection if you also need .size(), .isEmpty(), or .stream():
void method(Collection<String> strings) {
if (!strings.isEmpty()) { strings.stream()... }
}
// List if you also need .get(index):
void method(List<String> strings) {
strings.get(...)
}
// Don't declare a specific list implementation
// unless you're sure you need it:
void method(ArrayList<String> strings) {
??? // You don't want to limit yourself to just ArrayList
}
Innym przykładem może być zawsze deklarowanie zmiennej an InputStream
, chociaż zwykle jest to FileInputStream
lub BufferedInputStream
, ponieważ dzień wkrótce ty lub ktoś inny będziesz chciał użyć innego rodzaju InputStream
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55
Jeśli potrzebujesz prostej listy wielkości 1:
List<String> strings = new ArrayList<String>(Collections.singletonList("A"));
Jeśli potrzebujesz listy kilku obiektów:
List<String> strings = new ArrayList<String>();
Collections.addAll(strings,"A","B","C","D");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-27 21:31:06
Z guawa możesz napisać:
ArrayList<String> places = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata");
W Guawie istnieją również inne użyteczne konstruktory statyczne. Możesz przeczytać o nich tutaj .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-12 03:02:22
Z java-9 i wyżej, jak sugerowano w JEP 269: metody fabryki wygody dla zbiorów , można to osiągnąć za pomocą literałów kolekcji teraz za pomocą -
List<String> list = List.of("A", "B", "C");
Set<String> set = Set.of("A", "B", "C");
Podobne podejście miałoby zastosowanie również do Map
-
Map<String, String> map = Map.of("k1", "v1", "k2", "v2", "k3", "v3")
, który jest podobny do propozycja literałów kolekcji , jak stwierdził @coobird. Dodatkowo wyjaśnione w JEP, jak również-
Alternatywy
Rozważano zmiany językowe kilka razy i odrzucone:
Projekt Moneta Propozycja, 29 Marca 2009
Projekt Moneta Propozycja, 30 Marca 2009
JEP 186 dyskusja na temat lambda-dev, styczeń-marzec 2014
Język propozycje zostały odłożone w miejsce propozycji opartej na bibliotekach jako podsumowane w tej wiadomości.
Related: jaki jest sens przeciążonych metod fabrycznych dla zbiorów w Javie 9
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55
Literały kolekcji nie znalazły się w Javie 8, ale możliwe jest użycie interfejsu Stream API do inicjalizacji listy w jednej dość długiej linii:
List<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toList());
Jeśli musisz upewnić się, że Twoje List
jest ArrayList
:
ArrayList<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toCollection(ArrayList::new));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-03 23:21:48
import com.google.common.collect.ImmutableList;
....
List<String> places = ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-12 13:14:16
Można utworzyć metodę fabryczną:
public static ArrayList<String> createArrayList(String ... elements) {
ArrayList<String> list = new ArrayList<String>();
for (String element : elements) {
list.add(element);
}
return list;
}
....
ArrayList<String> places = createArrayList(
"São Paulo", "Rio de Janeiro", "Brasília");
Ale to nie jest dużo lepsze niż twoja pierwsza refaktoryzacja.
Dla większej elastyczności, może być ogólny:
public static <T> ArrayList<T> createArrayList(T ... elements) {
ArrayList<T> list = new ArrayList<T>();
for (T element : elements) {
list.add(element);
}
return list;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-04 21:29:06
W Javie 9 możemy łatwo zainicjalizować ArrayList
w jednej linii:
List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");
Lub
List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
To nowe podejście do Javy 9 ma wiele zalet w stosunku do poprzednich:
Zobacz ten post po więcej szczegółów -> Jaka jest różnica między listą.Of and Arrays.asList?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-04 22:29:01
O najbardziej kompaktowy sposób to:
Double array[] = { 1.0, 2.0, 3.0};
List<Double> list = Arrays.asList(array);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-15 11:44:15
Po prostu użyj poniższego kodu w następujący sposób.
List<String> list = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-12 02:57:48
Z kolekcjami Eclipse możesz napisać:
List<String> list = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
Możesz również być bardziej szczegółowy o typach i czy są one Mutowalne lub niezmienne.
MutableList<String> mList = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableList<String> iList = Lists.immutable.with("Buenos Aires", "Córdoba", "La Plata");
Możesz również zrobić to samo z zestawami i torbami:
Set<String> set = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
MutableSet<String> mSet = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet<String> iSet = Sets.immutable.with("Buenos Aires", "Córdoba", "La Plata");
Bag<String> bag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
MutableBag<String> mBag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableBag<String> iBag = Bags.immutable.with("Buenos Aires", "Córdoba", "La Plata");
Notatka: jestem committerem Dla Kolekcji Eclipse.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-01 01:53:10
Oto inny sposób:
List<String> values = Stream.of("One", "Two").collect(Collectors.toList());
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-01 00:49:20
(powinien być komentarz, ale zbyt długi, więc nowa odpowiedź). Jak wspomnieli inni, metoda Arrays.asList
ma stały rozmiar, ale nie jest to jedyny problem z nią. Nie radzi sobie też zbyt dobrze z dziedziczeniem. Na przykład, załóżmy, że masz następujące:
class A{}
class B extends A{}
public List<A> getAList(){
return Arrays.asList(new B());
}
Powyższe powoduje błąd kompilatora, ponieważ List<B>
(który jest zwracany przez tablice.asList) nie jest podklasą List<A>
, mimo że można dodawać obiekty typu B do obiektu List<A>
. Aby to obejść, musisz zrobić coś w stylu:
new ArrayList<A>(Arrays.<A>asList(b1, b2, b3))
To chyba najlepszy sposób, żeby to zrobić, esp. jeśli potrzebujesz nieograniczonej listy lub potrzebujesz użyć dziedziczenia.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-12 02:57:07
Możesz użyć poniższych instrukcji:
Fragment Kodu:
String [] arr = {"Sharlock", "Homes", "Watson"};
List<String> names = Arrays.asList(arr);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55
Jak Tom powiedział :
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
Ale ponieważ narzekałeś, że chcesz ArrayList, powinieneś najpierw wiedzieć, że ArrayList jest podklasą listy i możesz po prostu dodać tę linię:
ArrayList<String> myPlaces = new ArrayList(places);
Chociaż, to może sprawić, że będziesz narzekać na "wydajność".
W takim przypadku nie ma to dla mnie sensu, dlaczego, skoro Twoja lista jest predefiniowana, nie została zdefiniowana jako tablica (Ponieważ rozmiar jest znany w momencie inicjalizacji). A jeśli jest to opcja dla ty:
String[] places = {"Buenos Aires", "Córdoba", "La Plata"};
Jeśli nie zależy ci na drobnych różnicach wydajności, możesz również skopiować tablicę do ArrayList bardzo prosto:
ArrayList<String> myPlaces = new ArrayList(Arrays.asList(places));
Dobra, ale w przyszłości potrzebujesz czegoś więcej niż tylko nazwy miejsca, potrzebujesz też kodu kraju. Zakładając, że jest to wciąż predefiniowana lista, która nigdy się nie zmieni w czasie wykonywania, dobrze jest użyć zestawu enum
, który wymagałby ponownej kompilacji, gdyby lista musiała zostać zmieniona w przyszłości.
enum Places {BUENOS_AIRES, CORDOBA, LA_PLATA}
Would
enum Places {
BUENOS_AIRES("Buenos Aires",123),
CORDOBA("Córdoba",456),
LA_PLATA("La Plata",789);
String name;
int code;
Places(String name, int code) {
this.name=name;
this.code=code;
}
}
Enum ma statyczną metodę values
, która zwraca tablicę zawierającą wszystkie wartości enum w kolejności, w jakiej są zadeklarowane, np.:
for (Places p:Places.values()) {
System.out.printf("The place %s has code %d%n",
p.name, p.code);
}
W takim razie chyba nie potrzebowałbyś swojej ArrayList.
P. S.Randyaa zademonstrował kolejny miły sposób przy użyciu statycznej metody użytkowej zbiorów.addAll .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:48
Java 9 posiada następującą metodę tworzenia listy immutable :
List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");
, który można łatwo dostosować do tworzenia listy mutowalnej, jeśli jest to wymagane:
List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
Podobne metody są dostępne dla Set
i Map
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-06 09:57:49
List<String> names = Arrays.asList("2","@2234","21","11");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-23 13:18:51
Tak przy pomocy tablic można zainicjalizować listę tablic w jednej linii,
List<String> strlist= Arrays.asList("aaa", "bbb", "ccc");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-13 05:54:55
Możesz użyć StickyList
z Cactoos :
List<String> names = new StickyList<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-25 17:48:17
Spróbuj użyć tej linii kodu:
Collections.singletonList(provider)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-16 14:25:18
W Javie nie da się zrobić
ArrayList<String> places = new ArrayList<String>( Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Jak już wspomniano, musisz wykonać inicjalizację podwójnego nawiasu klamrowego:
List<String> places = new ArrayList<String>() {{ add("x"); add("y"); }};
Ale może to zmusić cię do dodania adnotacji @SuppressWarnings("serial")
lub wygenerowania szeregowego UUID, co jest denerwujące. Również większość formaterów kodu rozpakuje to do wielu instrukcji / wierszy.
Alternatywnie możesz zrobić
List<String> places = Arrays.asList(new String[] {"x", "y" });
Ale wtedy możesz chcieć zrobić @SuppressWarnings("unchecked")
.
Również według javadoc powinieneś być w stanie to zrobić:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
Ale nie jestem można go skompilować z JDK 1.6.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-13 22:44:20
Collections.singletonList(messageBody)
Jeśli potrzebujesz mieć listę jednego elementu !
Kolekcje {[7] } pochodzą z java.util pakiet.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-03 09:30:38
Najlepszy sposób na to:
package main_package;
import java.util.ArrayList;
public class Stackkkk {
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<Object>();
add(list, "1", "2", "3", "4", "5", "6");
System.out.println("I added " + list.size() + " element in one line");
}
public static void add(ArrayList<Object> list,Object...objects){
for(Object object:objects)
list.add(object);
}
}
Po prostu utwórz funkcję, która może mieć tyle elementów, ile chcesz i wywołaj ją, aby dodać je w jednej linii.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-27 21:35:25
Oto kod AbacusUtil
// ArrayList
List<String> list = N.asList("Buenos Aires", "Córdoba", "La Plata");
// HashSet
Set<String> set = N.asSet("Buenos Aires", "Córdoba", "La Plata");
// HashMap
Map<String, Integer> map = N.asMap("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);
// Or for Immutable List/Set/Map
ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet.of("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet.of("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);
// The most efficient way, which is similar with Arrays.asList(...) in JDK.
// but returns a flexible-size list backed by the specified array.
List<String> set = Array.asList("Buenos Aires", "Córdoba", "La Plata");
Deklaracja: jestem twórcą AbacusUtil.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-27 22:46:36
Dla mnie.asList() jest najlepsza i wygodna. Zawsze lubię inicjować w ten sposób. Jeśli jesteś początkującym w kolekcjach Java, chciałbym, abyś skierował inicjalizację ArrayList
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-07 05:37:12
Dlaczego nie zrobić prostej funkcji użytkowej, która to robi?
static <A> ArrayList<A> ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
"ll
" oznacza "dosłowną listę".
ArrayList<String> places = ll("Buenos Aires", "Córdoba", "La Plata");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-04 11:23:08
co ciekawe nikt-liner z drugim przeciążony Stream::collect
metoda jest wymieniona
ArrayList<String> places = Stream.of( "Buenos Aires", "Córdoba", "La Plata" ).collect( ArrayList::new, ArrayList::add, ArrayList::addAll );
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-04 15:04:11
W zasadzie można to zrobić w jednej linijce:
Arrays.asList(new MyClass[] {new MyClass("arg1"), new MyClass("arg2")})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-27 21:31:36