将原始长整型数组转换为长整型列表
问题描述:
这可能是一个很容易,headdesk的问题,但我的第一次尝试令人惊讶的完全失败了。我想要一个原始longs数组,并把它变成一个列表,我试图这样做:
This may be a bit of an easy, headdesk sort of question, but my first attempt surprisingly completely failed to work. I wanted to take an array of primitive longs and turn it into a list, which I attempted to do like this:
long[] input = someAPI.getSomeLongs();
List<Long> inputAsList = Arrays.asList(input); //Total failure to even compile!
正确的方法是什么?
答
我发现它很方便使用apache commons lang ArrayUtils( JavaDoc )
I found it convenient to do using apache commons lang ArrayUtils (JavaDoc)
long[] input = someAPI.getSomeLongs();
Long[] inputBoxed = ArrayUtils.toObject(input);
List<Long> inputAsList = Arrays.asList(inputBoxed);
它也有相反的API
long[] backToPrimitive = ArrayUtils.toPrimitive(objectArray);
EDIT:已更新,可提供完整转换评论和其他修正。
updated to provide a complete conversion to a list as suggested by comments and other fixes.