如何计算类的实例数

谁能告诉我如何计算一个类的实例数?

这是我的代码

public class Bicycle { //instance variables public int gear, speed, seatHeight; public String color; //constructor public Bicycle(int gear, int speed, int seatHeight, String color) { gear = 0; speed = 0; seatHeight = 0; color ="Unknown"; } //getters and setters public int getGear() { return gear; } public void setGear(int Gear) { this.gear = Gear; } public int getSpeed() { return speed; } public void setSpeed(int Speed){ this.speed = Speed; } public int getSeatHeight() { return seatHeight; } public void setSeatHeight(int SeatHeight) { this.seatHeight = SeatHeight; } public String getColor() { return color; } public void setColor(String Color) { this.color = Color; } }//end class public class Variable extends Bicycle { public Variable(int gear, int speed, int seatHeight, String color) { super(gear, speed, seatHeight, color); } }//end class public class Tester { public static void main(String args[]){ Bicycle bicycle1 = new Bicycle(0, 0, 0, null); bicycle1.setColor("red"); System.out.println("Color: "+bicycle1.getColor()); bicycle1.setSeatHeight(4); System.out.println("Seat Height: "+bicycle1.getSeatHeight()); bicycle1.setSpeed(10); System.out.println("Speed: "+bicycle1.getSpeed()); bicycle1.setGear(6); System.out.println("Gear: "+bicycle1.getGear()); System.out.println("");//space Bicycle bicycle2 = new Bicycle(0, 0, 0, null); bicycle2.setColor("black"); System.out.println("Color: "+bicycle2.getColor()); bicycle2.setSeatHeight(6); System.out.println("Seat Height: "+bicycle2.getSeatHeight()); bicycle2.setSpeed(12); System.out.println("Speed: "+bicycle2.getSpeed()); bicycle2.setGear(6); System.out.println("Gear: "+bicycle2.getGear()); System.out.println("");//space }//end method }//end class 

类变量用于保持创建的Bicycle类的实例数,计数器类创建Bicycle类的多个实例,并演示Bicycle类和类变量的工作方式。 我看了整个互联网,我似乎找不到任何东西,有人可以告诉我该怎么做,谢谢你提前:)

由于static变量只初始化一次,并且它们在所有实例之间共享,因此您可以:

 class MyClass { private static int counter; public MyClass() { //... counter++; } public static int getNumOfInstances() { return counter; } } 

阅读有关JLS – 8.3.1.1中 static字段的更多信息。 静态字段

如果一个字段被声明为static那么无论该类最终可以创建多少个实例(可能为零),都只存在该字段的一个化身static字段(有时称为类变量)在初始化类时实现(第12.4节)。

请注意, counter隐式设置为零

此外,您应该覆盖finalize方法以减少计数器

 public class Bicycle { ... public static int instances = 0; { ++instances; //separate counting from constructor } ... public Bicycle(int gear, int speed, int seatHeight, String color) { gear = 0; speed = 0; seatHeight = 0; color ="Unknown"; } @Override protected void finalize() { super.finalize(); --instances; } } 

您应该记住,静态变量是CLASS作用域的(每个实例没有一个,每个类只有一个)

然后,您可以演示实例减少:

 ... System.out.println("Count:" + Bicycle.getNumOfInstances()); // 2 bicycle1 = null; bicycle2 = null; System.gc(); // not guaranteed to collect but it will in this case Thread.sleep(2000); // you expect to check again after some time System.out.println("Count again:" + Bicycle.getNumOfInstances()); // 0 

为什么不使用静态计数器?

 public class Bicycle { private static int instanceCounter = 0; //instance variables public int gear, speed, seatHeight; public String color; //constructor public Bicycle(int gear, int speed, int seatHeight, String color) { gear = 0; speed = 0; seatHeight = 0; color ="Unknown"; instanceCounter++; } public int countInstances(){ return instanceCounter; } ........ 

请试试java的工具

 jmap -histo  

出局

  num #instances #bytes class name ---------------------------------------------- 1: 1105141 97252408 java.lang.reflect.Method 2: 3603562 86485488 java.lang.Double 3: 1191098 28586352 java.lang.String 4: 191694 27035744 [C 

一种基本方法是声明一个静态数字成员字段,每次调用构造函数时都会增加。

 public class Bicycle { //instance variables public int gear, speed, seatHeight; public String color; public static int bicycleCount = 0; //constructor public Bicycle(int gear, int speed, int seatHeight, String color) { gear = 0; speed = 0; seatHeight = 0; color ="Unknown"; bicycleCount++; } ... } 

你只需要在课堂上使用静态计数器。

 public class Bicycle { private static volatile int instanceCounter; public Bicycle() { instanceConter++; } public static int getNumOfInstances() { return instanceCounter; } protected void finalize() { instanceCounter--; } } 

正如许多评论中所提到的,建议不要使用finalize() ,因此可能有另一种方法来计算Bicycle实例 –

 public class Bicycle { private static final List> phantomReferences = new LinkedList>(); private static final ReferenceQueue referenceQueue = new ReferenceQueue(); private static final Object lock = new Object(); private static volatile int counter; private static final Runnable referenceCleaner = new Runnable() { public void run() { while (true) { try { cleanReferences(); } catch (Exception e) { e.printStackTrace(); } } } }; static { Thread t = new Thread(referenceCleaner); t.setDaemon(true); t.start(); } private Bicycle() { } public static Bicycle getNewBicycle() { Bicycle bicycle = new Bicycle(); counter++; synchronized (lock) { phantomReferences.add(new PhantomReference(new Bicycle(), referenceQueue)); } System.out.println("Bicycle added to heap, count: " + counter); return bicycle; } private static void cleanReferences() { try { PhantomReference reference = (PhantomReference) referenceQueue.remove(); counter--; synchronized (lock) { phantomReferences.remove(reference); } System.out.println("Bicycle removed from heap, count: " + counter); } catch (Exception e) { e.printStackTrace(); } } public static int getNumOfBicycles() { return counter; } } public class BicycleTest { public static void main(String[] args) { int i = 0; while (i++ < 1000) { Bicycle.getNewBicycle(); } while (Bicycle.getNumOfBicycles() > 0) { try { Thread.sleep(1000); System.gc(); // just a request } catch (Exception e) { e.printStackTrace(); } } } } 

或者,您可以使用初始化程序块和静态变量创建计数器。

 class SomeClass { static int counter; { counter++; } } 

初始化程序块被编译器复制到每个构造函数中,因此,无论您需要多少构造函数,都必须编写一次(如上面的链接所述)。 {}中的块在每次创建类的新对象时运行,并将变量计数器增加1。 当然,通过以下方式获得计数器:

 public int getCounter() { return counter; } 

或直接

 int numOfInstances = SomeClass.counter; 
 public class Number_Objects { static int count=0; Number_Objects(){ count++; } public static void main(String[] args) { Number_Objects ob1=new Number_Objects(); Number_Objects ob2=new Number_Objects(); Number_Objects obj3=new Number_Objects(); System.out.print("Number of objects created :"+count); } }