Konwertuj listę na tablicę w Javie [duplikat]
Jak mogę przekonwertować List
na Array
w Javie?
Sprawdź poniższy kod:
ArrayList<Tienda> tiendas;
List<Tienda> tiendasList;
tiendas = new ArrayList<Tienda>();
Resources res = this.getBaseContext().getResources();
XMLParser saxparser = new XMLParser(marca,res);
tiendasList = saxparser.parse(marca,res);
tiendas = tiendasList.toArray();
this.adaptador = new adaptadorMarca(this, R.layout.filamarca, tiendas);
setListAdapter(this.adaptador);
Muszę wypełnić tablicę tiendas
wartościami tiendasList
.
11 answers
Albo:
Foo[] array = list.toArray(new Foo[0]);
Lub:
Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array
Zauważ, że działa to tylko dla tablic typów referencyjnych. Dla tablic typów prymitywnych, użyj tradycyjnego sposobu:
List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
Aktualizacja:
Zaleca się teraz stosowanie list.toArray(new Foo[0]);
, a nie list.toArray(new Foo[list.size()]);
.
od JetBrains Intellij Idea inspection:
Istnieją dwa style do konwersji kolekcji na tablicę: albo za pomocą a pre-sized array (like c. ToArray(new String [C. size()])) lub użycie pustej tablicy (jak c. ToArray(new String[0]).
W starsze wersje Javy korzystające z pre-sized array były zalecane, ponieważ wywołanie odbicia, które jest konieczne do utworzenia tablicy o odpowiednim rozmiarze to było dość powolne. Jednak od późnych aktualizacji OpenJDK 6 to wezwanie była intrinsyfikowana, dzięki czemu wydajność wersji pustej tablicy ten sam, a czasem nawet lepszy, w porównaniu do pre-size wersja. Również przekazywanie pre-sized tablicy jest niebezpieczne dla równoczesnego lub zbieranie zsynchronizowane jako wyścig danych jest możliwe między Rozmiar i ToArray wywołanie, które może skutkować dodatkowymi nullami na końcu tablicy, jeśli zbiór był jednocześnie skurczony podczas operacji.
Kontrola ta pozwala śledzić Jednolity Styl: albo używając pustej tablicy (co jest zalecane w nowoczesną Javę) lub przy użyciu pre-size array (która może być szybsza w starsze wersje Javy lub JVMs oparte na hotspocie).
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-06-17 02:35:22
Alternatywa w Javie 8:
String[] strings = list.stream().toArray(String[]::new);
Od Java 11:
String[] strings = list.toArray(String[]::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
2020-11-02 09:36:23
Myślę, że jest to najprostszy sposób:
Foo[] array = list.toArray(new Foo[0]);
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
2013-01-03 11:19:39
Natknąłem się na ten fragment kodu, który go rozwiązuje.
//Creating a sample ArrayList
List<Long> list = new ArrayList<Long>();
//Adding some long type values
list.add(100l);
list.add(200l);
list.add(300l);
//Converting the ArrayList to a Long
Long[] array = (Long[]) list.toArray(new Long[list.size()]);
//Printing the results
System.out.println(array[0] + " " + array[1] + " " + array[2]);
Konwersja działa następująco:
- tworzy nową długą tablicę o rozmiarze oryginalnej listy
- konwertuje oryginalną tablicę ArrayList do tablicy przy użyciu nowo utworzonej tablicy
- rzuca tę tablicę do długiej tablicy (Long[]), którą odpowiednio nazwałem '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-01-23 10:07:20
Najlepsze co wymyśliłem bez Javy 8 było:
public static <T> T[] toArray(List<T> list, Class<T> objectClass) {
if (list == null) {
return null;
}
T[] listAsArray = (T[]) Array.newInstance(objectClass, list.size());
list.toArray(listAsArray);
return listAsArray;
}
Jeśli ktoś ma lepszy sposób na to, proszę się podzielić :)
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-13 12:36:44
To działa. Tak jakby.
public static Object[] toArray(List<?> a) {
Object[] arr = new Object[a.size()];
for (int i = 0; i < a.size(); i++)
arr[i] = a.get(i);
return arr;
}
Następnie główna metoda.
public static void main(String[] args) {
List<String> list = new ArrayList<String>() {{
add("hello");
add("world");
}};
Object[] arr = toArray(list);
System.out.println(arr[0]);
}
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-01-15 13:37:12
Dla ArrayList następujące prace:
ArrayList<Foo> list = new ArrayList<Foo>();
//... add values
Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);
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-10 21:19:56
To (odpowiedź Ondreja):
Foo[] array = list.toArray(new Foo[0]);
Jest najczęstszym idiomem, jaki widzę. Ci, którzy sugerują, że używasz rzeczywistego rozmiaru listy zamiast "0", nie rozumieją, co się tutaj dzieje. Wywołanie toArray nie dba o rozmiar ani zawartość podanej tablicy - potrzebuje tylko jej typu. Byłoby lepiej, gdyby wziął rzeczywisty typ, w którym to przypadku " Foo.class " byłoby dużo jaśniej. Tak, ten idiom generuje atrapy obiektu, ale włączenie rozmiaru listy oznacza, że generujesz większy atrapa obiektu. Ponownie, obiekt nie jest w żaden sposób używany; jest to tylko typ, który jest potrzebny.
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
2013-09-12 00:24:03
Przykład zaczerpnięty z tej strony: http://www.java-examples.com/copy-all-elements-java-arraylist-object-array-example
import java.util.ArrayList;
public class CopyElementsOfArrayListToArrayExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to ArrayList
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
/*
To copy all elements of java ArrayList object into array use
Object[] toArray() method.
*/
Object[] objArray = arrayList.toArray();
//display contents of Object array
System.out.println("ArrayList elements are copied into an Array.
Now Array Contains..");
for(int index=0; index < objArray.length ; index++)
System.out.println(objArray[index]);
}
}
/*
Output would be
ArrayList elements are copied into an Array. Now Array Contains..
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
2014-12-02 11:10:54
Możesz użyć API toArray () w następujący sposób,
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("ListItem1");
stringList.add("ListItem2");
String[] stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringList);
Wartości z tablicy to,
for(String value : stringList)
{
System.out.println(value);
}
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-07 22:09:25
Spróbuj tego:
List list = new ArrayList();
list.add("Apple");
list.add("Banana");
Object[] ol = list.toArray();
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-30 15:53:21