(取消)在Java中装箱原始数组 [英] (Un)boxing primitive arrays in Java

查看:91
本文介绍了(取消)在Java中装箱原始数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android Java世界中,是否有一种简便的方法(最好是一次调用)将 int 的数组转换为 ArrayList< Integer> ; 然后返回?在ArrayList上调用 toArray()会返回 Integer 的数组-不完全是我想要的。

in the Android Java world, is there a straighforward (ideally one-call) way to convert an array of int to an ArrayList<Integer> and back? Calling toArray() on the ArrayList returns an array of Integer - not quite what I want.

我可以轻松地手动执行一个循环(实际上已经做到了)。我想知道库/语言是否支持相同的语言。

I can easily do that by hand with a loop (already did, in fact). I'm wondering if the library/language supports the same.

编辑:谢谢,我已经写了自己的拳击手和拆箱手。我只是感到惊讶,语言/ RTL设计师自己没有想到这一点,特别是在原始类型被设计为不适合集合的情况下。

thanks all, I already wrote my own boxer and unboxer. I'm just surprised the language/RTL designers didn't think of it themselves, especially with primitive types being by design ineligible for collections.

推荐答案

使用番石榴 Ints.asList(int ...) Ints.toArray(Collection< Integer>)):

int[] intArray = ...
List<Integer> intArrayAsList = Ints.asList(intArray);
int[] intArray2 = Ints.toArray(intArrayAsList);

请注意,例如 Arrays.asList Ints.asList 返回一个列表,该列表是给定数组的视图。您不能对其进行添加或删除,但是可以设置特定索引处的值。您还可以根据需要将其复制到新的 ArrayList

Note that like Arrays.asList, Ints.asList returns a list that is a view of the given array. You can't add to or remove from it, but you can set the value at a specific index. You can also copy it to a new ArrayList if you want:

List<Integer> arrayList = Lists.newArrayList(Ints.asList(intArray));

番石榴对所有原始类型都具有相同的方法。

Guava has the same methods for all primitive types.

这篇关于(取消)在Java中装箱原始数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆