简体   繁体   English

如何将Long []写入包裹?

[英]How can I write Long[] to a parcel?

I am trying to write a Long[] array to a parcel, but it only accepts a long[] array as an argument. 我正在尝试将Long []数组写入一个包裹,但它仅接受long []数组作为参数。

( The method writeLongArray(long[]) in the type Parcel is not applicable for the arguments (Long[]) ) Parcel类型的方法writeLongArray(long [])不适用于参数(Long [])

public class SomeClass implements Parcelable {

private Long minutes, lastUpdated;

...
...

 @Override 
 public void writeToParcel(Parcel out, int flags) {
    out.writeLongArray(new Long[] {this.minutes, this.lastUpdated });
 }

This seems to work, but is this allowed: 这似乎可行,但这是允许的:

     out.writeLongArray(new long[] {this.minutes, this.lastUpdated });

This: 这个:

out.writeLongArray(new long[] {this.minutes, this.lastUpdated });

works, because you are using an array initializer with array elements listed out explicitly. 之所以可行,是因为您正在使用数组初始化器,其中数组元素已明确列出。 Each of those elements is being unboxed into a primitive long, and so the code both compiles and runs successfully, nothing wrong with that. 这些元素中的每一个都被解包成一个原始的整整整整整天 ,因此代码可以编译并成功运行,这没有错。 If you had a collection of Long's, you could perform the conversion in a loop: 如果您有Long的集合,则可以循环执行转换:

long[] unboxedLongs = new long[boxedLongs.length];
for(int i = 0; i < boxedLongs.length; i++) {
    unboxedLongs[i] = boxedLongs[i].longValue();
 }

Which is tedious to write, every time you want to convert a boxed array to its unboxed equivalent, but there is no direct conversion available through the SDK (afaik). 每次要将盒装数组转换为非盒装数组时,编写起来都很繁琐,但没有通过SDK(afaik)进行的直接转换。 There are third party libraries that would enable you to write shorter code though - for example with the Apache Commons Lang ArrayUtils class : 有一些第三方库可以使您编写较短的代码,例如使用Apache Commons Lang ArrayUtils类

long[] unboxedLongs = ArrayUtils.toPrimitive(boxedLongs);

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

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