简体   繁体   English

将对象数组转换为其原始类型数组

[英]Converting an array of objects to an array of their primitive types

If you have an array of Java objects which have a primitive type (for example Byte, Integer, Char, etc).如果您有一组具有原始类型(例如 Byte、Integer、Char 等)的 Java 对象。 Is there a neat way I can convert it into an array of the primitive type?有没有一种巧妙的方法可以将其转换为原始类型的数组? In particular can this be done without having to create a new array and loop through the contents.特别是可以在不必创建新数组并循环遍历内容的情况下完成此操作。

So for example, given例如,给定

Integer[] array

what is the neatest way to convert this into将其转换为最简洁的方法是什么

int[] intArray

Unfortunately, this is something we have to do quite frequently when interfacing between Hibernate and some third party libraries over which we have no control.不幸的是,当在 Hibernate 和一些我们无法控制的第三方库之间进行交互时,这是我们必须经常做的事情。 It seems this would be a quite common operation so I would be surprised if there's no shortcut.看起来这将是一个很常见的操作,所以如果没有捷径,我会感到惊讶。

Thanks for your help!谢谢你的帮助!

Once again, Apache Commons Lang is your friend. Apache Commons Lang再次成为您的朋友。 They provide ArrayUtils.toPrimitive() which does exactly what you need.他们提供了ArrayUtils.toPrimitive()来满足你的需求。 You can specify how you want to handle nulls.您可以指定处理空值的方式。

With streams introduced in Java 8 this can be done:使用 Java 8 中引入的可以做到这一点:

int[] intArray = Arrays.stream(array).mapToInt(Integer::intValue).toArray();

However, there are currently only primitive streams for int , long and double .但是,目前只有intlongdouble原始流。 If you need to convert to another primitive type such as byte the shortest way without an external library is this:如果您需要转换为另一种基本类型,例如byte则无需外部库的最短方法是:

byte[] byteArray = new byte[array.length];
for(int i = 0; i < array.length; i++) byteArray[i] = array[i];

Or the for loop can be replaced with a stream if you want:或者,如果需要,可以将 for 循环替换为流:

IntStream.range(0, array.length).forEach(i -> byteArray[i] = array[i]);

All of these will throw a NullPointerException if any of your elements are null .如果您的任何元素为null所有这些都将抛出NullPointerException

Unfortunately, there's nothing in the Java platform that does this.不幸的是,Java 平台中没有任何东西可以做到这一点。 Btw, you also need to explicitly handle null elements in the Integer[] array (what int are you going to use for those?).顺便说一句,您还需要显式处理Integer[]数组中的null元素(您将使用什么int ?)。

Using Guava :使用番石榴

int[] intArray = Ints.toArray(Arrays.asList(array));

Documentation:文档:

In particular can this be done without having to create a new array and loop through the contents.特别是可以在不必创建新数组并循环遍历内容的情况下完成此操作。

You can't convert an array of Integer to int (ie you can't change the type of the elements of an array) in Java.在 Java 中不能将 Integer 数组转换为 int(即不能更改数组元素的类型)。 So you either must create a new int[] array and copy the value of the Integer objects into it or you can use an adapter:因此,您必须创建一个新的 int[] 数组并将 Integer 对象的值复制到其中,或者您可以使用适配器:

class IntAdapter {
    private Integer[] array;
    public IntAdapter (Integer[] array) { this.array = array; }
    public int get (int index) { return array[index].intValue(); }
}

This can make your code a little more readable and the IntAdapter object will only consume a few bytes of memory.这可以使您的代码更具可读性,并且 IntAdapter 对象将只消耗几个字节的内存。 The big advantage of an adapter is that you can handle special cases here:适配器的一大优势是您可以在此处处理特殊情况:

class IntAdapter {
    private Integer[] array;
    public int nullValue = 0;
    public IntAdapter (Integer[] array) { this.array = array; }
    public int get (int index) { 
        return array[index] == null ? nullValue : array[index].intValue();
    }
}

Another solution is to use Commons Primitives which contains lots of predefined adapters.另一种解决方案是使用包含许多预定义适配器的Commons Primitives In your case, have a look at ListIntList .在您的情况下,请查看ListIntList

Or just do it the easy way if you gonna do it only once.或者如果你只做一次,就用简单的方法来做。 But you haven't talked about Integer!=null case.但是你还没有谈到 Integer!=null 的情况。

    //array is the Integer array
    int[] array2 = new int[array.length];
    int i=0;
    for (Integer integer : array) {
        array2[i] = integer.intValue();
        i++;
    }

using Dollar is simple as:使用Dollar很简单:

Integer[] array = ...;
int[] primitiveArray = $(array).toIntArray();

Here is a generic solution for all primitive types这是所有原始类型的通用解决方案

/**
 * Convert Collection to equivalent array of primitive type
 * @param <S> [in] Object type of source collection
 * @param tcls [in] class of the primitive element
 * @param q [in] source collection
 * @return Equivalent Array of tcls-elements, requires cast to "tcls"[]
 */
public static <S> Object asPrimitiveArray(Class<?> tcls, Collection<S> q)
{
    int n = q.size();
    Object res = Array.newInstance(tcls, n);
    Iterator<S> i = q.iterator();
    int j = 0;
    while (i.hasNext())
    {
        Array.set(res, j++, i.next());
    }
    return res;
}

/**
 * Convert Object array to equivalent array of primitive type
 * @param <S> [in] Object type of source array
 * @param tcls [in] class of the primitive element
 * @param s [in] source array
 * @return Equivalent Array of tcls-elements, requires cast to "tcls"[]
 */
public static <S> Object asPrimitiveArray(Class<?> tcls, S[] s)
{
    return asPrimitiveArray(tcls, Arrays.asList(s));
} 

For Integer to int conversion整数到整数的转换

Integer[] a = ...
int[] t = (int[]) asPrimitiveArray(int.class, a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM