Java 计算现有对象的数量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20159104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count number of existing objects
提问by Taylor
So I'm making a die class that can create and roll a die, return the value and the size. I'm trying to figure out how to tell the program how many of them have been created so that I can have a response be different based on how many there are. IE I want the response from printDie to be Die Value: 5 if there is only one die, and Die 1 Value: 5 if there is more than one.
所以我正在制作一个可以创建和掷骰子的 die 类,返回值和大小。我试图弄清楚如何告诉程序已经创建了多少个,以便我可以根据有多少做出不同的响应。IE 我希望来自 printDie 的响应为 Die Value: 5 如果只有一个模具,而 Die 1 Value: 5 如果有多个。
Here's my code so far.
到目前为止,这是我的代码。
package com.catalyse.die;
import java.util.Random;
public class Die
{
// instance variables
private int myDieValue;
private int myDieSides;
private Random myRandom;
// Dice Class Constructors
public Die()
{
this.myDieValue = 1;
this.myDieSides = 4;
}
public Die(int numSides)
{
if ((numSides < 4) || (numSides > 100)) {
System.out.println("Error! You cannot have more than 100 sides or less than four!");
System.exit(0);
}
else {
myDieSides = numSides;
}
}
// getter methods
public int getDieSides()
{
return myDieSides;
}
public int getDieValue()
{
return myDieValue;
}
// setter methods
private void setDieSides(int newNumSides)
{
myDieSides = newNumSides;
}
public void rollDie()
{
Random rand = new Random();
int i = (rand.nextInt(myDieSides) + 1);
myDieValue = i;
}
public void printDie(int dieNum)
{
if (dieNum == 1) {
System.out.println("Die Value: "+myDieValue);
}
else {
System.out.println("Die "+dieNum+" Value: "+myDieValue);
}
}
}
}
采纳答案by SudoRahul
You can have static field in your class which could be incremented in the constructor always. The reason why is it should be static
is because, static
fields are shared by all instances of a class, thus a local copy of the field won't be created for each of the instances you create.
您可以在类中拥有静态字段,该字段可以始终在构造函数中递增。之所以应该这样做,static
是因为static
字段由类的所有实例共享,因此不会为您创建的每个实例创建该字段的本地副本。
private static int counter = 0;
public Die()
{
counter++;
// Other stuffs
}
// Have a getter method for the counter so that you can
// get the count of instances created at any point of time
public static int getCounter() {
return counter;
}
And then you can call the above method in your calling method like this
然后你可以像这样在你的调用方法中调用上面的方法
void someMethodInAnotherClass() {
int instanceCount = Die.getCounter(); // You need to call static method using the Class name
// other stuffs.
}
回答by Christian
Use an static member, that is a 'class' variable, not a 'instance' variable:
使用静态成员,即“类”变量,而不是“实例”变量:
private static int count = 0;
In the constructor:
在构造函数中:
public Die()
{
count++;
this.myDieValue = 1;
this.myDieSides = 4;
}
And a getter:
还有一个吸气剂:
public static int getCount() {
return count;
}
回答by Paul Samsotha
Use a static variable
使用静态变量
public class Die{
static int dieCount = 0;
public Die(){
dieCount++;
}
}
Every time a Die
object is created, the count will increase
每次Die
创建对象时,计数都会增加
public static void main(String[] args){
Die die1 = new Die();
Die die2 = new Die();
int count = Die.dieCount;
}
回答by Dhiral Pandya
See what is my solution for counting objects in my application
看看我的应用程序中计数对象的解决方案是什么
import java.util.Map;
import java.util.TreeMap;
public abstract class ObjectCounter {
private static Map<String, Long> classNameCount = new TreeMap<String, Long>();
public ObjectCounter() {
String key = this.getClass().getName();
if (classNameCount.containsKey(key)) {
classNameCount.put(key, classNameCount.get(key) + 1);
} else {
classNameCount.put(key, 1L);
}
}
public static <T extends ObjectCounter> long getCount(Class<T> c) {
String key = c.getName();
if (classNameCount.containsKey(key)) {
return classNameCount.get(key);
} else {
return 0;
}
}
public static long totalObjectsCreated() {
long totalCount = 0;
for (long count : classNameCount.values()) {
totalCount += count;
}
return totalCount;
}
}
Now extends ObjectCounter class
现在扩展 ObjectCounter 类
See below
见下文
package com.omt.factory;
public class Article extends ObjectCounter {
}
Now all your other classes are extending Article classes
现在你所有的其他类都在扩展文章类
package com.omt.factory;
public class Bio extends Article {
}
Now here is our main class
现在这是我们的主类
package com.omt.factory;
public class Main {
public static void main(String... a) {
Bio b = new Bio();
Bio b1 = new Bio();
Bio b2 = new Bio();
Bio b3 = new Bio();
Bio b4 = new Bio();
com.omt.temp.Bio bio = new com.omt.temp.Bio();
// Total Objects are created
System.out.println("Total Objects Created By Application :" + ObjectCounter.totalObjectsCreated());
// Get Number Of Objects created for class.
System.out.println("[" + com.omt.temp.Bio.class.getName() + "] Objects Created :"
+ ObjectCounter.getCount(com.omt.temp.Bio.class));
System.out.println("[" + Bio.class.getName() + "] Objects Created :" + ObjectCounter.getCount(Bio.class));
System.out.println("[" + Maths.class.getName() + "] Objects Created :" + ObjectCounter.getCount(Maths.class));
}
}