Jak przekonwertować Arraylistę zawierającą liczby całkowite do prymitywnej tablicy int?

Próbuję przekonwertować ArrayList zawierający Obiekty Integer do prymitywnego int [] z poniższym fragmentem kodu, ale jest to błąd czasu kompilacji. Czy możliwa jest konwersja w Javie?

List<Integer> x =  new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);
Author: Jonas, 2009-04-05

12 answers

Można konwertować, ale nie sądzę, aby było coś wbudowanego, aby zrobić to automatycznie:

public static int[] convertIntegers(List<Integer> integers)
{
    int[] ret = new int[integers.size()];
    for (int i=0; i < ret.length; i++)
    {
        ret[i] = integers.get(i).intValue();
    }
    return ret;
}

(zauważ, że spowoduje to odrzucenie NullPointerException, jeśli {[2] } lub jakikolwiek element w nim jest null.)

EDIT: zgodnie z komentarzami, możesz użyć iteratora listy, aby uniknąć nieprzyjemnych kosztów z listami takimi jak LinkedList:

public static int[] convertIntegers(List<Integer> integers)
{
    int[] ret = new int[integers.size()];
    Iterator<Integer> iterator = integers.iterator();
    for (int i = 0; i < ret.length; i++)
    {
        ret[i] = iterator.next().intValue();
    }
    return ret;
}
 188
Author: Jon Skeet,
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-01-12 17:40:09

Jeśli używasz java-8 istnieje również inny sposób, aby to zrobić.

int[] arr = list.stream().mapToInt(i -> i).toArray();

To co robi to:

  • uzyskanie Stream<Integer> z listy
  • W przeciwieństwie do Javy, Java nie jest w stanie tworzyć żadnych elementów składowych, które nie są w stanie tworzyć żadnych elementów składowych.]}
  • uzyskanie tablicy int przez wywołanie toArray

Można również jawnie wywołać intValue poprzez odniesienie do metody, i. E:

int[] arr = list.stream().mapToInt(Integer::intValue).toArray();

Warto również wspomnieć, że możesz uzyskać NullPointerException, Jeśli masz jakieś null odniesienie na liście. Można tego łatwo uniknąć, dodając warunek filtrowania do potoku strumienia w następujący sposób:

                       //.filter(Objects::nonNull) also works
int[] arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray();

Przykład:

List<Integer> list = Arrays.asList(1, 2, 3, 4);
int[] arr = list.stream().mapToInt(i -> i).toArray(); //[1, 2, 3, 4]

list.set(1, null); //[1, null, 3, 4]
arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray(); //[1, 3, 4]
 131
Author: Alexis 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
2016-07-19 17:49:17

Apache Commons ma klasę ArrayUtils, która ma metodę toPrimitive (), która robi dokładnie to.

import org.apache.commons.lang.ArrayUtils;
...
    List<Integer> list = new ArrayList<Integer>();
    list.add(new Integer(1));
    list.add(new Integer(2));
    int[] intArray = ArrayUtils.toPrimitive(list.toArray(new Integer[0]));

Jednak, jak pokazał Jon, całkiem łatwo jest to zrobić samemu, zamiast korzystać z zewnętrznych bibliotek.

 59
Author: Björn,
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-05 09:00:32

Google Guava

Google Guava zapewnia schludny sposób, aby to zrobić, dzwoniąc Ints.toArray.

List<Integer> list = ...;
int[] values = Ints.toArray(list);
 52
Author: Snehal,
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 20:43:40

Uważam, że iteracja przy użyciu iteratora listy jest lepszym pomysłem, ponieważ list.get(i) może mieć słabą wydajność w zależności od implementacji listy:

private int[] buildIntArray(List<Integer> integers) {
    int[] ints = new int[integers.size()];
    int i = 0;
    for (Integer n : integers) {
        ints[i++] = n;
    }
    return ints;
}
 40
Author: Matthew Willis,
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-11 18:56:59

Użycie dolara powinno być dość proste:

List<Integer> list = $(5).toList(); // the list 0, 1, 2, 3, 4  
int[] array = $($(list).toArray()).toIntArray();

Planuję ulepszyć DSL w celu usunięcia pośredniego połączenia toArray()

 6
Author: dfa,
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-02-01 20:14:28

Jeśli używasz kolekcji Eclipse , możesz użyć metody collectInt(), aby przełączyć się z kontenera obiektu na prymitywny kontener int.

List<Integer> integers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
MutableIntList intList =
  ListAdapter.adapt(integers).collectInt(i -> i);
Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, intList.toArray());

Jeśli możesz przekonwertować ArrayList na FastList, możesz pozbyć się adaptera.

Assert.assertArrayEquals(
  new int[]{1, 2, 3, 4, 5},
  Lists.mutable.with(1, 2, 3, 4, 5)
    .collectInt(i -> i).toArray());

Notatka: jestem committerem Dla Kolekcji Eclipse.

 3
Author: Craig P. Motlin,
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-05 03:15:54

Dziwi mnie, że zachęcamy do jednorazowych niestandardowych metod, gdy doskonale dobra, dobrze używana biblioteka, taka jak Apache Commons, już rozwiązała problem. Chociaż rozwiązanie jest trywialne, jeśli nie absurdalne, nieodpowiedzialne jest zachęcanie do takiego zachowania ze względu na długoterminową konserwację i dostępność.

Po prostu wybierz Apache Commons

 1
Author: Andrew F.,
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-06-18 18:19:56

Możesz po prostu skopiować go do tablicy:

int[] arr = new int[list.size()];
for(int i = 0; i < list.size(); i++) {
    arr[i] = list.get(i);
}
Nie za wyszukane; ale, hej, to działa...
 1
Author: sagiksp,
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-08-13 15:28:26

Ten segment kodu działa dla mnie, spróbuj tego

Integer[] arr = x.toArray(new Integer[x.size()]);
 0
Author: user3444748,
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-11-07 17:52:07
   List<Integer> list = new ArrayList<Integer>();

    list.add(1);
    list.add(2);

    int[] result = null;
    StringBuffer strBuffer = new StringBuffer();
    for (Object o : list) {
        strBuffer.append(o);
        result = new int[] { Integer.parseInt(strBuffer.toString()) };
        for (Integer i : result) {
            System.out.println(i);
        }
        strBuffer.delete(0, strBuffer.length());
    }
 -4
Author: CodeMadness,
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-05-03 12:49:07
Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);

Dostęp arr jak normalny int[].

 -6
Author: snn,
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
2011-09-14 20:22:04