How to find the number of objects in the heap

前端 未结 10 1826
离开以前
离开以前 2020-11-29 07:31

How can I find the number of live objects on the heap in Java program?

10条回答
  •  甜味超标
    2020-11-29 08:07

    public class NumOfObjects {
    
        static int count=0;
        {
            count++;
        }
        public static void main(String[] args)
        {
            NumOfObjects no1=new NumOfObjects();
            System.out.println("no1:" + count);//1
    
            NumOfObjects no2=new NumOfObjects();
            System.out.println("no2:"+ count); //2
            for (int i=0; i<10;i++)
            {
                NumOfObjects noi=new NumOfObjects();    
            }
            System.out.println("Total objects:"+count);// 12 
        }
    }
    

提交回复
热议问题