有谁能告诉我如何计算班级的实例数量?
这是我的代码
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类和类变量的工作方式。我看了整个互联网,我似乎找不到任何东西,有人可以告诉我该怎么做,谢谢你提前:)
答案 0 :(得分:15)
由于static
变量只初始化一次,并且它们在所有实例之间共享,您可以:
class MyClass {
private static int counter;
public MyClass() {
//...
counter++;
}
public static int getNumOfInstances() {
return counter;
}
}
详细了解JLS - 8.3.1.1. static Fields中的static
字段:
如果声明了一个字段
static
,那么就会存在该字段的一个化身,无论最终可以创建多少个实例(可能为零)。一个static
字段,有时称为类变量,在初始化类时实现(第12.4节)。
请注意,counter
隐式设置为零
答案 1 :(得分:3)
此外,您应该覆盖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
答案 2 :(得分:2)
请尝试使用java的工具
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
String accessKey = "YOUR_ACCESS_KEY";
String apiUrl = "https://api.apiflash.com/v1/urltoimage";
URL url = new URL(String.format("%s?access_key=%s&url=google.com&width=800&height=600", apiUrl, accessKey));
InputStream inputStream = url.openStream();
OutputStream outputStream = new FileOutputStream("screenshot.jpeg");
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) != -1) {
outputStream.write(b, 0, length);
}
inputStream.close();
outputStream.close();
}
}
Out put
jmap -histo <PDID>
答案 3 :(得分:1)
为什么不使用静态计数器?
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;
}
........
答案 4 :(得分:0)
一种基本方法是声明一个静态数字成员字段,每次调用构造函数时都会增加。
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++;
}
...
}
答案 5 :(得分:0)
你只需要在课堂上使用静态计数器。
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<PhantomReference<Bicycle>> phantomReferences = new LinkedList<PhantomReference<Bicycle>>();
private static final ReferenceQueue<Bicycle> referenceQueue = new ReferenceQueue<Bicycle>();
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<Bicycle>(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();
}
}
}
}
答案 6 :(得分:0)
或者,您可以使用initializer block和静态变量创建计数器。
HWND Window = FindWindow("Notepad", "Untitled - Notepad");
if (Window != nullptr)
{
SetParent(Window, hwnd);
SetWindowPos(Window, nullptr, 0, 0, 0, 0, SWP_NOSIZE);
RedrawWindow(Window, nullptr, nullptr, RDW_INVALIDATE);
ShowWindow(Window, SW_SHOW);
}
初始化程序块被编译器复制到每个构造函数中,因此,无论您需要多少构造函数,都必须编写一次(如上面的链接所述)。 {}中的块在每次创建类的新对象时运行,并将变量计数器增加1。 当然,通过以下方式获得计数器:
class SomeClass
{
static int counter;
{
counter++;
}
}
或直接
public int getCounter()
{
return counter;
}
答案 7 :(得分:0)
如果要基于创建的对象数对实例进行计数和测试,则可以使用循环查看实际发生的情况。创建一个构造函数并使用一个静态计数器
public class CountInstances {
public static int count;
public CountInstances() {
count++;
}
public int getInstaces() {
return count;
}
public static void main(String []args) {
for(int i= 0; i<10; i++) {
new CountInstances();
}
System.out.println(CountInstances.count);
}
}
答案 8 :(得分:-1)
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);
}
}