public class Car { String name; public Car(String name){ this.name = name; }}public class Test01 {public static void main(String[] args) { int[] a = new int[3]; a[0] = 20; a[2] = 32; a[1] = 45; Car[] cars = new Car[4]; cars[0] = new Car("奔驰"); }}比如这个程序,堆中分配4个空间给数组Car,3个空间给int,每个空间占几个字节?另外Char占几个字节?
java中一个int占4个字节,由于java是unicode编码,一个char可以占两个字节,可以存储一个汉字。一个String,要看有几个字母或者几个汉字,一个英文字母就是一个字节,一个汉字就是两个字节,以此类推计算。
如果String串为纯英文,那么一个英文字母是一个字符,长度为1,占1个字节,不会出错,但如果String串中包含中文,一个中文汉字也是一个字符,长度为1,但是却占多个字节(具体占几个字节跟使用的编码有关),如果数据中包含中文,数据的长度就很有可能会超过数据库中对应字段的长度限制
Java程序计算各种对象所占内存的大小的方法。基类:publicabstractclass SizeOf { privatefinal Runtime s_runtime = Runtime.getRuntime(); protectedabstract Object newInstance(); publicint size() throws Exception { runGC(); Object[] objects = new Object[count]; long heap1 = usedMemory(); for (int i = -1; i < count; ++i) { Object object = null; object = newInstance(); objects[i] = object; object = null; runGC(); heap1 = usedMemory(); } } runGC(); long heap2 = usedMemory(); finalint size = Math.round(((float) (heap2 - heap1)) / count); for (int i = 0; i < count; ++i) { objects[i] = null; } } privatevoid runGC() throws Exception { for (int r = 0; r < 4; ++r) { _runGC(); } } privatevoid _runGC() throws Exception { long usedMem1 = usedMemory(); long usedMem2 = Long.MAX_VALUE; for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++i) { s_runtime.runFinalization(); s_runtime.gc(); Thread.currentThread().yield(); usedMem2 = usedMem1; usedMem1 = usedMemory(); } } privatelong usedMemory() { return s_runtime.totalMemory() - s_runtime.freeMemory(); } } 子类:publicclass SizeOfObject extends SizeOf { protected Object newInstance() { } publicstaticvoid main(String[] args) throws Exception { SizeOf sizeOf = new SizeOfObject(); System.out.println("所占内存:" + sizeOf.size() + "字节"); } } 输出为:所占内存:8字节