Oracle Interview Question
Web DevelopersMaybe this:
long l1 = Runtime.freeMemory();
obj.clone();
long l2 = Runtime.freeMemory();
System.out.println((l1-l2)+" bytes");
Although the javadoc for Runtime.freeMemory() says that this method returns only an approximate value.
(Correcting my earlier post)
Better to do the cloning in a loop because if the obj size is just few bytes like 5-6 bytes then the freeMemory() might give same result for l1 and l2 as its an approximation.
So:
long l1 = Runtime.freeMemory();
n=10;
for(int i=1;i<=n;i++){
obj.clone();
}
long l2 = Runtime.freeMemory();
System.out.println(((l1-l2)/n)+" bytes");
But the clone is not a deep clone...If the object contains another user-defined class, does this work?
It can be solved by bit option.
{{public class PrintSize{
public static void main(String[] argv){
int x = ~0;
int i=0;
while (0 != x){
//System.out.println("x: " + x);
x >>>=1;i++;
}
System.out.println("int size is "+i);
}
}
}}
Output: int size is 32
ByteArrayOutputStream bao = new ByteArrayOutputStream();
- Anonymous August 24, 2009ObjectOutputStream oos = new ObjectOutputStream(bao);
oos.writeObject(obj);
oos.flush();
int size = bao.size();
oos.close();