gpt4 book ai didi

java - 在单个二维数组中存储多种数据类型

转载 作者:行者123 更新时间:2023-11-30 05:57:51 24 4
gpt4 key购买 nike

我需要在二维数组中存储多种数据类型(主要是 int 或 string)。使用 Object[][] 确实可以解决问题。但这是一个好方法吗?

Object[][] 数组如何保留堆空间?我的意思是,按照哪种数据类型?是否会导致资源浪费?

我试图做这样的事情:-

Object[][] dataToBeWritten={ {"帕米",34,45},
{"罗恩","x",""},
{"蜘蛛","x",""}
};

编辑:如果存在的话,您也可以建议任何更好的替代方案..

最佳答案

参见How to calculate the memory usage of a Java arrayMemory usage of Java objects: general guide .

For example, let's consider a 10x10 int array. Firstly, the "outer" array has its 12-byte object header followed by space for the 10 elements. Those elements are object references to the 10 arrays making up the rows. That comes to 12+4*10=52 bytes, which must then be rounded up to the next multiple of 8, giving 56. Then, each of the 10 rows has its own 12-byte object header, 4*10=40 bytes for the actual row of ints, and again, 4 bytes of padding to bring the total for that row to a multiple of 8. So in total, that gives 11*56=616 bytes. That's a bit bigger than if you'd just counted on 10*10*4=400 bytes for the hundred "raw" ints themselves.

我认为这仅适用于 Hotspot。对任何对象的引用只是链接整数,每个 4 字节,无论实际对象如何,或者对象是否为 null。不过,对象本身的备用要求是一个完全不同的故事,因为在创建数组时没有保留空间或类似的东西。

关于java - 在单个二维数组中存储多种数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5102385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com