如何使用 Parcelable 发送多维数组?
我应该使用 Parcelable 吗?因为这似乎不接受多维数组,例如 int[][]
(我需要在活动之间发送数据)
Should I use Parcelable? Because that does not seem to accept multi-dimensional arrays like for example int[][]
(I need to send data between activities)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
等数载,海棠开2024-12-29 13:19:44
我知道这对游戏来说已经很晚了,但这是我使用的解决方案:
private void write2DimArray(int[][] array, Parcel parcel) {
parcel.writeInt(array.length);
for(int[] arrayDim1 : array) {
parcel.writeInt(arrayDim1.length);
parcel.writeIntArray(arrayDim1);
}
}
private int[][] read2DimArray(Parcel parcel) {
int[][] array = new int[parcel.readInt()][];
for(int i = 0; i < array.length; i++) {
int arraySize = parcel.readInt();
array[i] = new int[arraySize];
parcel.readIntArray(array[i]);
}
return array;
}
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
数组在 Java 中是协变的(它们都扩展了 Object)。
因此,您可以将数组的数组(例如
int[][]
)分配给Object[]
数组,因为数组是一个对象:int [][]
表示int[]
数组,而int[]
是一个Object
。对于泛型,如果您有一个类型
T
和一个数组T[]
,则将T
定义为int[]
会导致该数组恰好是int[][]
。希望这有帮助。
Arrays are covariant in Java (and they all extend Object).
Therefore, you can assign an array of arrays (like
int[][]
) to anObject[]
array, simply because an array is an object:int[][]
means an array ofint[]
andint[]
is anObject
.With generics, if you have a type
T
and an arrayT[]
, definingT
asint[]
would result in that array being exactlyint[][]
.Hope this helps.