Konwersja tablicy prymitywnych longów na Listę longów
To może być trochę łatwe, headdesk rodzaju pytanie, ale moja pierwsza próba zaskakująco całkowicie nie powiodła się. Chciałem wziąć szereg prymitywnych długów i przekształcić je w listę, co próbowałem zrobić w ten sposób: {]}
long[] input = someAPI.getSomeLongs();
List<Long> inputAsList = Arrays.asList(input); //Total failure to even compile!
Jaki jest właściwy sposób, aby to zrobić?
14 answers
Uznałem, że jest to wygodne do zrobienia przy użyciu Apache commons lang ArrayUtils ( JavaDoc, Maven dependency )
import org.apache.commons.lang3.ArrayUtils;
...
long[] input = someAPI.getSomeLongs();
Long[] inputBoxed = ArrayUtils.toObject(input);
List<Long> inputAsList = Arrays.asList(inputBoxed);
Posiada również odwrotne API
long[] backToPrimitive = ArrayUtils.toPrimitive(objectArray);
EDIT: zaktualizowano, aby zapewnić pełną konwersję na Listę zgodnie z sugestiami komentarzy i innych poprawek.
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-05-31 21:50:45
Od Javy 8 możesz teraz używać do tego strumieni:
long[] arr = {1,2,3,4};
List<Long> list = Arrays.stream(arr).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
2014-04-16 18:41:11
import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;
List<Long> longs = Arrays.asList(ArrayUtils.toObject(new long[] {1,2,3,4}));
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-06-02 18:32:43
Hallidave i jpalecek mają właściwy pomysł-iterację nad tablicą-ale nie wykorzystują funkcji dostarczonej przez ArrayList
: Ponieważ Rozmiar listy jest znany w tym przypadku powinieneś go określić podczas tworzenia ArrayList
.
List<Long> list = new ArrayList<Long>(input.length);
for (long n : input)
list.add(n);
W ten sposób nie są tworzone żadne niepotrzebne tablice, które mogą być odrzucane przez ArrayList
, ponieważ okazują się zbyt krótkie, a puste "sloty" nie są marnowane, ponieważ ArrayList
przeceniają swoje wymagania dotyczące przestrzeni. Oczywiście., jeśli nadal będziesz dodawać elementy do listy, potrzebna będzie nowa tablica pomocnicza.
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:41
Jako inną możliwość, Biblioteka Guava zapewnia to jako Longs.asList()
, z podobnymi klasami użyteczności dla innych prymitywnych typów.
import com.google.common.primitives.Longs;
long[] input = someAPI.getSomeLongs();
List<Long> output = Longs.asList(input);
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-10-19 08:21:39
Trochę bardziej gadatliwy, ale to działa:
List<Long> list = new ArrayList<Long>();
for (long value : input) {
list.add(value);
}
W twoim przykładzie wygląda na to, że tablice.asList() interpretuje dane wejściowe jako listę tablic long [] zamiast listy Long. Trochę zaskakujące, na pewno. Autoboxing po prostu nie działa tak, jak chcesz w tym przypadku.
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
2009-04-16 00:28:44
Nie, Nie ma automatycznej konwersji z tablicy typu prymitywnego do tablicy ich pudełkowych typów referencyjnych. You can only do
long[] input = someAPI.getSomeLongs();
List<Long> lst = new ArrayList<Long>();
for(long l : input) lst.add(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
2009-04-16 00:28:55
Piszę małą bibliotekę na te problemy:
long[] input = someAPI.getSomeLongs();
List<Long> = $(input).toList();
Jeśli Ci zależy, sprawdź to 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
2010-01-31 22:04:18
Inny sposób z Java 8.
long[] input = someAPI.getSomeLongs();
LongStream.of(input).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
2016-08-25 09:56:11
Łącząc odpowiedzi Pawła i Toma otrzymujemy to
@SuppressWarnings("unchecked")
public static <T> List<T> asList(final Object array) {
if (!array.getClass().isArray())
throw new IllegalArgumentException("Not an array");
return new AbstractList<T>() {
@Override
public T get(int index) {
return (T) Array.get(array, index);
}
@Override
public int size() {
return Array.getLength(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
2013-08-01 00:59:37
Inny sposób z Java 8.
final long[] a = new long[]{1L, 2L};
final List<Long> l = Arrays.stream(a).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-05-23 11:55:10
Jeśli chcesz podobną semantykę do Arrays.asList
, musisz napisać (lub użyć cudzej) implementacji List
(prawdopodobnie przez AbstractList
. Powinna mieć taką samą implementację jak Arrays.asList
, tylko wartości box i unbox.
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
2009-04-16 00:38:25
Możesz użyć transmorph:
Transmorph transmorph = new Transmorph(new DefaultConverters());
List<Long> = transmorph.convert(new long[] {1,2,3,4}, new TypeReference<List<Long>>() {});
Działa również, jeśli source jest tablicą ints na przykład.
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-01-20 06:10:29
Wiem, że to pytanie jest wystarczająco stare, ale... możesz również napisać własną metodę konwersji:
@SuppressWarnings("unchecked")
public static <T> List<T> toList(Object... items) {
List<T> list = new ArrayList<T>();
if (items.length == 1 && items[0].getClass().isArray()) {
int length = Array.getLength(items[0]);
for (int i = 0; i < length; i++) {
Object element = Array.get(items[0], i);
T item = (T)element;
list.add(item);
}
} else {
for (Object i : items) {
T item = (T)i;
list.add(item);
}
}
return list;
}
Po dołączeniu go za pomocą importu statycznego, możliwe użycie może być:
long[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<Long> list = toList(array);
Lub
List<Long> list = toList(1l, 2l, 3l, 4l, 5l, 6l, 7l, 8l, 9l);
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-10-16 16:40:21