【问题标题】:Count number of existing objects计算现有对象的数量
【发布时间】:2013-12-08 04:10:38
【问题描述】:

所以我正在制作一个可以创建和滚动骰子、返回值和大小的骰子类。我试图弄清楚如何告诉程序已经创建了多少,以便我可以根据有多少做出不同的响应。 IE 我希望 printDie 的响应是 Die Value: 5 如果只有一个 die,Die 1 Value: 5 如果有多个。

这是我目前的代码。

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);
    }
}

}

【问题讨论】:

  • 注意:Java 没有解构函数,因此通过使用静态字段,如果删除一个字段,计数将不会反映此更改。
  • 你提供的信息很不错,但我得问你,你说的一个被删除到底是什么意思?由于没有析构函数,所以没有删除。我猜你的意思是说,垃圾收集,可能? :)

标签: java object methods constructor


【解决方案1】:

看看我的应用程序中计算对象的解决方案是什么

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;
    }

} 

现在扩展了 ObjectCounter 类

见下文

package com.omt.factory;

public class Article extends ObjectCounter {

}

现在你所有的其他类都在扩展 Article 类

package com.omt.factory;

public class Bio extends Article {

}

现在这是我们的主要课程

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));

    }

}

From this article

【讨论】:

    【解决方案2】:

    使用静态变量

    public class Die{
        static int dieCount = 0;
    
        public Die(){
            dieCount++;
        }
    }
    

    每创建一个Die对象,计数就会增加

    public static void main(String[] args){
        Die die1 = new Die();
        Die die2 = new Die();
    
        int count = Die.dieCount;
    
    }
    

    【讨论】:

      【解决方案3】:

      您可以在您的类中拥有静态字段,该字段可以在构造函数中始终递增。之所以应该是 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;
      }
      

      然后你可以像这样在你的调用方法中调用上述方法

      void someMethodInAnotherClass() {
          int instanceCount = Die.getCounter(); // You need to call static method using the Class name
          // other stuffs.
      }
      

      【讨论】:

      • 太棒了,同样的代码,新问题。当我尝试测试该类时,Roll die 给了我一个 nullpointerexception。模具一 = 新模具(); One.rollDie(); One.getDieValue();线程“主”java.lang.NullPointerException 中的异常
      • 虽然这应该是另一个问题,但我会为你解答。你有 2 个构造函数。一个接受一个值来设置myDieSides,另一个不接受。尝试调用另一个,它接受一个值。 Die One = new Die(6);
      • 在扩展版的测试中,我有三个 die,一个是 new Die(5) 和 new Die(99),我都试过了,它们都抛出了相同的异常。跨度>
      • 我建议您将其作为一个新问题发布,并附上完整的错误堆栈跟踪和问题的确切场景。它需要得到应有的关注。另外,从目前的情况来看,我真的不能说更多。这就是为什么,考虑创建一个新问题! :)
      • 当一个对象被取消引用时会发生什么,我们如何减少counter
      【解决方案4】:

      使用静态成员,即“类”变量,而不是“实例”变量:

      private static int count = 0;
      

      在构造函数中:

      public Die()
      {
          count++;
          this.myDieValue = 1;
          this.myDieSides = 4;
      }
      

      还有一个吸气剂:

      public static int getCount() {
          return count;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-23
        • 1970-01-01
        • 2011-07-25
        • 1970-01-01
        • 2012-01-03
        • 2020-07-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多