通过Java代码实现对象、List类集、数组、Map及常用数据类型等占用字节大小的代码示例,详情参见代码示例部分。
package Test;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.List;
public class ByteSizeUtil {
/**
* @desc 对象、List类集、数组、Map及常用数据类型等占用字节大小
* @param
* @return
*/
public static int getByteSize( HashMap<String,Object> hashMap){
int byteSize=0;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(baos);
os.writeObject(hashMap);
os.close();
byteSize=baos.size();
System.out.println("所占字节 "+byteSize+" 字节");
//System.out.println("所占"+byteSize/1024+" KB");
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
return byteSize;
}
public static int getByteSize(List<Integer> datas) {
int byteSize=0;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(baos);
os.writeObject(datas);
os.close();
byteSize=baos.size();
System.out.println("所占字节 "+byteSize+" 字节");
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
return byteSize;
}
public static <V> void main(String[] args) throws Exception{
int n = 2021;
HashMap<String,Object> hashMap = new HashMap<String, Object>();
//测试添加数据
for (int i = 0; i < n; i++) {
hashMap.put(String.valueOf(n), n);
}
getByteSize(hashMap);
}
}