【问题标题】:How to add the value of all the objects?如何添加所有对象的值?
【发布时间】:2015-11-23 23:14:38
【问题描述】:

假设我们有一个 SCORE 课程。它具有三个对象 s1、s2 和 s3。 SCORE 有一个属性 RUNS。如何添加所有对象的运行? SCORE 有一个内部方法 int TOTALSCORE()。因此,当调用该方法时,它应该返回总分。

我应该如何调用该方法?喜欢 s1.TOTALSCORE() 吗?还是其他方式?

【问题讨论】:

  • 那么发布一些您尝试过的代码怎么样?
  • 通常“类”没有元素,但您应该组织一个元素列表。您可以将此列表提取到静态类方法Score.totalScore()
  • 不清楚你在问什么。您是说Score 类将包含您需要求和的三个对象引用。或者你是说你有三个Score 对象并且需要一些机制来总结它们? “RUNS”属性在哪里适合?
  • 今天早些时候,您问了一个类似的问题 (stackoverflow.com/questions/32284213/…)。我认为你应该多学习一下类。

标签: java class object methods


【解决方案1】:

这是一个小的概念证明:

public class Score {

private static ReferenceQueue<Score> scoreRefQueue = new ReferenceQueue<Score>();

private static List<WeakReference<Score>> runs = new ArrayList<WeakReference<Score>>();

static { // remove references to instances that are Garbage Collected
    new Thread(new Runnable() {
        @Override
        public void run() {
            while(true) try {
                Object scoreRef = scoreRefQueue.remove(); // blocks until next reference is available
                synchronized(runs) {                      // synch access with summing iterator
                    runs.remove(scoreRef);
                }
            } catch(Throwable t) {
                // ignore
            }
        }
    }).start();
}

/**
 * The factory method
 */
public static Score getInstance() {
    final Score score = new Score();
    final WeakReference<Score> scoreRef = new WeakReference<Score>(score, scoreRefQueue);
    synchronized(runs) {
        runs.add(scoreRef);
    }
    return score;
}

private int total;

private Score() {
    // prevent creating instances outside this class
}

/**
 * The service method
 */
public static int totalScore() {
    int totalScore = 0;
    synchronized(runs) { // synch access with cleanup thread
        for(WeakReference<Score> scoreRef : runs) {
            final Score score = scoreRef.get();
            if(score != null) {
                totalScore += score.total;
            }
        }
    }
    return totalScore;
}

}

我们的想法是不允许在工厂方法#getInstance() 之外创建实例。使用 Wea​​kReferences 跟踪实例以允许它们的垃圾收集。该列表由在参考队列上等待的服务线程更新。希望这会有所帮助。

【讨论】:

  • 在类确实需要一个所有类实例列表的情况下,这是一个好方法。所以如果你确定你需要一个所有元素的全局列表,使用这种方式。 WeakReferences 很酷,我根本不知道。
【解决方案2】:

在极少数情况下,您想要的东西可能是合理的,但通常该类并不知道它的所有元素。总分适用于分数元素的集合,可能是列表或集合。

所以你会这样做:

class Score {
  int value;
  // ...
  public static int totalScore(Collection<Score> scores){ 
    int sum = 0;
    for (Score s: scores){
      sum += s.value;
    }
    return sum;
  }
}

你会在外面

List<Score> myBagForScores = new ArrayList<>();
Score e1 = new Score...
myBagForScores.add(e1);
// e2, e3 and so on
int sum = Score.totalScore(myBagForScores);

希望有帮助!

【讨论】:

    猜你喜欢
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 2022-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多