Tworzenie ArrayList z tablicy
Mam tablicę, która jest inicjalizowana TAK:
Element[] array = {new Element(1), new Element(2), new Element(3)};
Chciałbym przekonwertować tę tablicę do obiektu klasy ArrayList.
ArrayList<Element> arraylist = ???;
30 answers
new ArrayList<>(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
2017-06-29 18:37:46
Podane:
Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) };
Najprostszą odpowiedzią jest:
List<Element> list = Arrays.asList(array);
To zadziała. Ale pewne zastrzeżenia:
- lista zwrócona z listy asList ma stały rozmiar. Tak więc, jeśli chcesz mieć możliwość dodawania lub usuwania elementów ze zwracanej listy w kodzie, musisz zawinąć go w nową
ArrayList
. W przeciwnym razie dostanieszUnsupportedOperationException
. - lista zwrócona z {[4] } jest wspierana przez oryginalną tablicę. Jeśli zmodyfikujesz oryginalną tablicę, lista zostanie zmodyfikowana jako cóż. To może być zaskakujące.
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-11-07 14:22:02
(Stary wątek, ale tylko 2 grosze jak nikt nie wspomni o Guawie czy innych libach i innych szczegółach)
Jeśli Możesz, Użyj Guawy
Warto zwrócić uwagę na sposób Guava, który znacznie upraszcza te przekręty:]}Użycie
Dla listy niezmiennej
Użyj ImmutableList
klasa i jej of()
oraz copyOf()
metody fabryczne (elementy nie mogą być null):
List<String> il = ImmutableList.of("string", "elements"); // from varargs
List<String> il = ImmutableList.copyOf(aStringArray); // from array
Dla Mutable Lista
Użyj Lists
klasa i jej newArrayList()
metody fabryczne:
List<String> l1 = Lists.newArrayList(anotherListOrCollection); // from collection
List<String> l2 = Lists.newArrayList(aStringArray); // from array
List<String> l3 = Lists.newArrayList("or", "string", "elements"); // from varargs
Zwróć również uwagę na podobne metody dla innych struktur danych w innych klasach, na przykład w Sets
.
Dlaczego Guava?
Główną atrakcją może być zmniejszenie bałaganu ze względu na generyki dla bezpieczeństwa typu, ponieważ stosowanie metod fabrycznych Guava pozwala na wywnioskowanie typów przez większość czasu. Jednak ten argument ma mniej woda od Jawa 7 przybył z nowym operatorem diamond.Ale nie jest to jedyny powód (a Java 7 nie jest jeszcze wszędzie): składnia stenograficzna jest również bardzo przydatna, a metody inicjalizatorów, jak pokazano powyżej, pozwalają pisać bardziej ekspresyjny kod. Wykonujesz w jednym wywołaniu co zajmuje 2 z obecnymi kolekcjami Javy.
Jeśli nie możesz...
Dla listy niezmiennej
Użyj JDK ' s Arrays
klasa i jej asList()
metoda fabryczna, zapakowane w Collections.unmodifiableList()
:
List<String> l1 = Collections.unmodifiableList(Arrays.asList(anArrayOfElements));
List<String> l2 = Collections.unmodifiableList(Arrays.asList("element1", "element2"));
Zauważ, że zwracany typ dla asList()
jest List
używającym konkretnej implementacji ArrayList
, ale nie jest java.util.ArrayList
. Jest to typ wewnętrzny, który emuluje ArrayList
, ale w rzeczywistości bezpośrednio odwołuje się do przekazanej tablicy i sprawia, że jest ona "zapisywana" (modyfikacje są odzwierciedlane w tablicy).
Zabrania modyfikacji za pomocą niektórych metod Api List
poprzez proste rozszerzenie AbstractList
(więc dodawanie lub usuwanie elementów jest nieobsługiwane), jednak pozwala na wywołanie set()
, aby nadpisać elementy. Tak więc ta lista nie jest tak naprawdę niezmienna i wywołanie asList()
powinno być owinięte Collections.unmodifiableList()
.
Zobacz następny krok, jeśli potrzebujesz zmiennej listy.
Dla listy zmiennej
To samo co wyżej, ale owinięte rzeczywistym java.util.ArrayList
:
List<String> l1 = new ArrayList<String>(Arrays.asList(array)); // Java 1.5 to 1.6
List<String> l1b = new ArrayList<>(Arrays.asList(array)); // Java 1.7+
List<String> l2 = new ArrayList<String>(Arrays.asList("a", "b")); // Java 1.5 to 1.6
List<String> l2b = new ArrayList<>(Arrays.asList("a", "b")); // Java 1.7+
Do celów edukacyjnych: dobry stary podręcznik sposób
// for Java 1.5+
static <T> List<T> arrayToList(final T[] array) {
final List<T> l = new ArrayList<T>(array.length);
for (final T s : array) {
l.add(s);
}
return (l);
}
// for Java < 1.5 (no generics, no compile-time type-safety, boo!)
static List arrayToList(final Object[] array) {
final List l = new ArrayList(array.length);
for (int i = 0; i < array.length; i++) {
l.add(array[i]);
}
return (l);
}
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-13 17:02:11
Ponieważ to pytanie jest dość stare, dziwi mnie, że nikt jeszcze nie zaproponował najprostszej formy:
List<Element> arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));
Począwszy od Javy 5, Arrays.asList()
pobiera parametr varargs i nie musisz jawnie konstruować tablicy.
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-29 16:25:34
new ArrayList<T>(Arrays.asList(myArray));
Upewnij się, że myArray
jest tego samego typu co T
. Jeśli na przykład spróbujesz utworzyć List<Integer>
z tablicy int
, otrzymasz błąd kompilatora.
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-02-13 17:04:38
Inny sposób (chociaż zasadniczo równoważny wydajności rozwiązania new ArrayList(Arrays.asList(array))
:
Collections.addAll(arraylist, 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
2012-04-03 23:28:52
Prawdopodobnie potrzebujesz listy, a nie ArrayList. W takim razie możesz po prostu zrobić:
List<Element> arraylist = 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
2008-10-01 14:45:02
Java 9
W Java 9 , możesz użyć List.of
statyczna metoda fabryczna w celu utworzenia litery List
. Coś takiego:
List<Element> elements = List.of(new Element(1), new Element(2), new Element(3));
To zwróci immutable lista zawierająca trzy elementy. Jeśli chcesz mutable lista, przekaż tę listę do konstruktora ArrayList
:
new ArrayList<>(List.of(// elements vararg))
JEP 269: metody fabryki wygody dla zbiorów
JEP 269 dostarcza kilka wygodnych metod fabrycznych dla kolekcji Java API. Te niezmienne statyczne metody fabryczne są wbudowane w List
, Set
, oraz Map
interfejsy w Javie 9 i nowszych.
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-07-29 07:19:18
Kolejna aktualizacja, prawie kończąca Rok 2014, możesz to zrobić również z Java 8:
ArrayList<Element> arrayList = Stream.of(myArray).collect(Collectors.toCollection(ArrayList::new));
Kilka znaków zostałoby zapisanych, gdyby to mógł być tylko List
List<Element> list = Stream.of(myArray).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
2014-11-25 20:48:36
Aby przekonwertować tablicę na tablicę ArrayList, programiści często robią to:
List<String> list = Arrays.asList(arr);// this is wrong way..
Arrays.asList()
zwróci ArrayList, który jest private static class inside Arrays
, nie jest to java.util.Klasy ArrayList. The java.util.Arrays.ArrayList
klasa ma metody set(), get(), contains()
, ale nie ma żadnych metod dodawania elementów, więc jej rozmiar jest stały.
Aby utworzyć prawdziwą Arraylistę, musisz wykonać:
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr));
Konstruktor ArrayList może przyjąć Typ zbioru , który jest również typem super dla java.util.Arrays.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-11-20 17:16:20
Jeśli używasz:
new ArrayList<T>(Arrays.asList(myArray));
Ty możesz utworzyć i wypełnić dwie listy ! Wypełnienie dwukrotnie dużej listy jest dokładnie tym, czego nie chcesz robić, ponieważ utworzy ona kolejną tablicę Object[]
za każdym razem, gdy pojemność będzie wymagała rozszerzenia.
Na szczęście implementacja JDK jest szybka i Arrays.asList(a[])
jest bardzo dobrze wykonana. Tworzy rodzaj ArrayList o nazwie Arrays.ArrayList, gdzie Dane obiektu [] wskazują bezpośrednio na tablicę.
// in Arrays
@SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
//still in Arrays, creating a private unseen class
private static class ArrayList<E>
private final E[] a;
ArrayList(E[] array) {
a = array; // you point to the previous array
}
....
}
Niebezpieczną stroną jest to, że jeśli Zmień początkową tablicę, zmienisz listę !Na pewno tego chcesz ? Może tak, może nie.
Jeśli nie, najbardziej zrozumiałym sposobem jest zrobienie tego:
ArrayList<Element> list = new ArrayList<Element>(myArray.length); // you know the initial capacity
for (Element element : myArray) {
list.add(element);
}
Lub jak powiedział @glglgl, możesz utworzyć inną niezależną ArrayList za pomocą:
new ArrayList<T>(Arrays.asList(myArray));
Uwielbiam używać Collections
, Arrays
, albo guawa. Ale jeśli to nie pasuje, lub nie czujesz, po prostu napisz inną nieelegancką linię zamiast.
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-29 19:22:08
W Java 9
możesz użyć:
List<String> list = List.of("Hello", "World", "from", "Java");
List<Integer> list = List.of(1, 2, 3, 4, 5);
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-08-12 11:22:20
Zgodnie z pytaniem odpowiedź w Javie 1.7 brzmi:
ArrayList<Element> arraylist = new ArrayList<Element>(Arrays.<Element>asList(array));
Jednak lepiej zawsze używać interfejsu:
List<Element> arraylist = Arrays.<Element>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
2015-05-17 22:07:25
// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray);
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-01-07 06:04:45
Możesz konwertować za pomocą różnych metod
List<Element> list = Arrays.asList(array);
List<Element> list = new ArrayList();
Collections.addAll(list, array);Arraylist list = new Arraylist();
list.addAll(Arrays.asList(array));
Więcej szczegółów można znaleźć w http://javarevisited.blogspot.in/2011/06/converting-array-to-arraylist-in-java.html
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-18 16:30:20
Można to również zrobić za pomocą stream w Javie 8.
List<Element> elements = Arrays.stream(array).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
2016-02-06 08:56:21
Od Javy 8 istnieje łatwiejszy sposób transformacji:
public static <T> List<T> fromArray(T[] array) {
return Arrays.stream(array).collect(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
2018-01-04 08:56:57
-
Jeśli zobaczymy definicję metody
Arrays.asList()
otrzymasz coś takiego:public static <T> List<T> asList(T... a) //varargs are of T type.
Więc możesz zainicjować
arraylist
w następujący sposób:List<Element> arraylist = Arrays.asList(new Element(1),new Element(2),new Element(3));
Uwaga : każdy
new Element(int args)
będzie traktowany jako indywidualny obiekt i może być przekazany jakovar-args
. -
Na to pytanie może być też inna odpowiedź.
Jeśli zobaczysz deklarację dla metodyjava.util.Collections.addAll()
, otrzymasz coś takiego:public static <T> boolean addAll(Collection<? super T> c, T... a);
Więc ten kod jest również przydatne do tego
Collections.addAll(arraylist, 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
2016-11-08 09:52:07
Tak jak wszyscy mówili, to się stanie
new ArrayList<>(Arrays.asList(array))
A powszechnym sposobem tworzenia tablic jest obserwowalne tablice
ObservableList: lista, która umożliwia słuchaczom śledzenie zmian w momencie ich wystąpienia.
Dla Javy SE możesz spróbować
FXCollections.observableArrayList(new Element(1), new Element(2), new Element(3));
Zgodnie z Oracle Docs
Obserwowalny() Tworzy nową pustą listę obserwowalną, która jest wspierana przez arraylist. obserwowalny (E... pozycje) Tworzy nową obserwowalną lista tablic z dodanymi do niej elementami.
Update Java 9
Również w Javie 9 to trochę proste:
List<String> list = List.of("element 1", "element 2", "element 3");
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-08-16 10:44:48
Innym prostym sposobem jest dodanie wszystkich elementów z tablicy do nowej ArrayList za pomocą pętli for-each.
ArrayList<Element> list = new ArrayList<>();
for(Element e : array)
list.add(e);
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-12-16 20:32:39
Podane:
Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) };
Użycie:
List<Element> listArray = 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
2017-04-22 07:23:01
Jeśli tablica jest typu prymitywnego, podane odpowiedzi nie będą działać. Ale od Javy 8 można używać:
int[] array = new int[5];
Arrays.stream(array).boxed().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-07-10 02:37:18
Mimo, że jest wiele doskonale napisanych odpowiedzi na to pytanie, dodam swoje wkłady.
Powiedz, że masz Element[] array = { new Element(1), new Element(2), new Element(3) };
Nową ArrayList można utworzyć w następujący sposób
ArrayList<Element> arraylist_1 = new ArrayList<>(Arrays.asList(array));
ArrayList<Element> arraylist_2 = new ArrayList<>(
Arrays.asList(new Element[] { new Element(1), new Element(2), new Element(3) }));
// Add through a collection
ArrayList<Element> arraylist_3 = new ArrayList<>();
Collections.addAll(arraylist_3, array);
I bardzo dobrze wspierają wszystkie operacje ArrayList
arraylist_1.add(new Element(4)); // or remove(): Success
arraylist_2.add(new Element(4)); // or remove(): Success
arraylist_3.add(new Element(4)); // or remove(): Success
Ale następujące operacje zwracają tylko Widok listy ArrayList, a nie rzeczywistą ArrayList.
// Returns a List view of array and not actual ArrayList
List<Element> listView_1 = (List<Element>) Arrays.asList(array);
List<Element> listView_2 = Arrays.asList(array);
List<Element> listView_3 = Arrays.asList(new Element(1), new Element(2), new Element(3));
W związku z tym, będą one dawać błąd podczas próby wykonania niektórych operacji ArrayList
listView_1.add(new Element(4)); // Error
listView_2.add(new Element(4)); // Error
listView_3.add(new Element(4)); // Error
Więcej na liście reprezentacji tablicy link.
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:26:29
Najprostszym sposobem jest dodanie następującego kodu. Sprawdzone.
String[] Array1={"one","two","three"};
ArrayList<String> s1= new ArrayList<String>(Arrays.asList(Array1));
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-03 08:38:28
Możemy łatwo przekonwertować tablicę na ArrayList
.
Używamy metody addAll()
Collection interface do kopiowania zawartości z jednej listy do drugiej.
Arraylist arr = new Arraylist();
arr.addAll(Arrays.asList(asset));
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-18 19:15:54
Inne rozwiązanie Java8 (mogłem pominąć odpowiedź wśród dużego zestawu. Jeśli tak, to przepraszam). tworzy to Arraylistę (w przeciwieństwie do listy) tzn. można usuwać elementy
package package org.something.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Junk {
static <T> ArrayList<T> arrToArrayList(T[] arr){
return Arrays.asList(arr)
.stream()
.collect(Collectors.toCollection(ArrayList::new));
}
public static void main(String[] args) {
String[] sArr = new String[]{"Hello", "cruel", "world"};
List<String> ret = arrToArrayList(sArr);
// Verify one can remove an item and print list to verify so
ret.remove(1);
ret.stream()
.forEach(System.out::println);
}
}
Wyjście jest...
Hello
Świat
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-20 08:40:25
Już wszyscy dostarczyli wystarczająco dobrą odpowiedź na twój problem. Teraz ze wszystkich sugestii musisz zdecydować, który będzie pasował do Twoich wymagań. Istnieją dwa rodzaje kolekcji, które musisz wiedzieć. Jedną z nich jest niezmodyfikowana kolekcja, a drugą kolekcja, która pozwoli na późniejszą modyfikację obiektu.
Więc tutaj podam krótki przykład dla dwóch przypadków użycia.
-
Immutable collection creation:: gdy nie chcesz modyfikować obiektu collection po creation
List<Element> elementList = Arrays.asList(array)
-
Mutable Collection creation:: kiedy możesz chcieć zmodyfikować utworzony obiekt collection po utworzeniu.
List<Element> elementList = new ArrayList<Element>(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
2017-07-25 06:03:11
Możesz to zrobić w Javie 8 w następujący sposób
ArrayList<Element> list = (ArrayList<Element>)Arrays.stream(array).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-08-02 14:03:02
Element[] array = {new Element(1), new Element(2), new Element(3)};
List<Element> elements=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
2017-06-11 09:03:39
Możesz utworzyć ArrayList
używając Cactoos (jestem jednym z twórców):
List<String> names = new StickyList<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
);
Nie ma gwarancji, że obiekt rzeczywiście będzie należał do klasy ArrayList
. Jeśli potrzebujesz tej gwarancji, zrób to:
ArrayList<String> list = new ArrayList<>(
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-26 12:19:51