java 如何仅通过一个方法调用重置所有对象值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11401183/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:56:35  来源:igfitidea点击:

How can I reset all object values with only one method call?

java

提问by

Basically, I want to create Counter objects, all they have to do is hold number values. And in my resetCounters method, I would like to reset each object's values. This is probably very easy, but I'm a newb.

基本上,我想创建 Counter 对象,它们所要做的就是保存数字值。在我的 resetCounters 方法中,我想重置每个对象的值。这可能很容易,但我是新手。

public class Counter
{
    Random number = new Random();

    Counter()
    {
        Random number = new Random();
    }

    public Random getNumber()
    {
        return number;
    }

    public void setNumber(Random number)
    {
        this.number = number;
    }

    public static void main(String[] args) 
    {
        Counter counter1 = new Counter();
        Counter counter2 = new Counter();
        Counter counter3 = new Counter();
        Counter counter4 = new Counter();
        Counter counter5 = new Counter();

    }

    public static void resetCounters()
    {

    }
    }

采纳答案by krlmlr

First option: Memorize each instance of Counter.

第一个选项:记住Counter.

Collect each instance of Counterin some static collection. To reset all, simply iterate over all items in the collection. But strong references are too strong for this-- make sure it's a collection of weak references.

收集Counter一些静态集合中的每个实例。要重置所有,只需遍历集合中的所有项目。但是强引用对于这个来说太强了——确保它是弱引用的集合。

Remarks:

评论:

  1. Using weak references will avoid the issue that the Counterobjects exist indefinitely only because of their reference from within the static collection. Objects that are referred to only by weak references are eventually collected by the garbage collector.
  2. The collection of every instance can be achieved by declaring the Counterconstructor privateand allowing only construction through a staticmember function which will also do the registration. (Or use some other incarnation of the Factorypattern.) I believe a factory is the way to go here, since each construction of an object has to carry out also a side effect. But perhaps it will make do to have the Counterconstructor register thiswith the static collection.
  1. 使用弱引用将避免Counter对象仅因为它们来自静态集合内的引用而无限期存在的问题。仅由弱引用引用的对象最终由垃圾收集器收集。
  2. 每个实例的集合可以通过声明Counter构造函数private并只允许通过static成员函数进行构造来实现,该成员函数也将进行注册。(或者使用工厂模式的其他一些化身。)我相信工厂是这里的方法,因为对象的每个构造也必须执行副作用。但也许可以让Counter构造函数注册this到静态集合。

Second option: Generation counter

第二个选项:代计数器

Keep a staticgeneration counter of type long, and also a copy of this counter in each instance. When resetting all counters, just increase the staticgeneration counter. The getNumber()method will then check the staticgeneration counter against its own copy and reset the counter if the staticgeneration counter has changed.

保留static类型为 的生成计数器long,以及每个实例中此计数器的副本。重置所有计数器时,只需增加static生成计数器。getNumber()然后,该方法将static对照其自己的副本检查生成计数器,如果static生成计数器已更改,则重置计数器。

(I don't really know the "official" name for this trick. How to zero out array in O(1)?)

(我真的不知道这个技巧的“官方”名称。 如何将 O(1) 中的数组归零?

回答by Louis Wasserman

Since we have no idea what the context is, we can't narrow down the specific thing you should do is, but the options that occur to me immediately are...

由于我们不知道上下文是什么,因此我们无法缩小您应该做的具体事情的范围,但是我立即想到的选项是......

1: If the counters have distinct meanings beyond "counter1, counter2, counter3," then they could be static class variables (with more useful names).

1:如果计数器在“counter1、counter2、counter3”之外有不同的含义,那么它们可能是静态类变量(具有更有用的名称)。

   public class Counter {
       static Counter counter1 = new Counter();
       ...
       public void resetCounters() {
         counter1.clear();
         counter2.clear();
          ...
        }
      }

2: If you just want several distinct counters, and they have no particular meaning by themselves, andyou know that there will only ever be five of them, then you should use an array:

2:如果你只想要几个不同的计数器,而它们本身没有特别的意义,而且你知道它们永远只有五个,那么你应该使用数组:

public class Counter {
  public static void main(String[] args) {
    Counter[] counters = {new Counter(), new Counter(), new Counter(), new Counter(), new Counter()};
    ...
  }
  static void resetCounters(Counter[] counters) {
    for (Counter c : counters) {
      c.reset();
    }
  }
}

Or, if you're planning to have an arbitrary number of them, you might try one of the fancier factory patterns. It really depends on what the context is, what you're actually trying to do, and what the point of the exercise is.

或者,如果您计划拥有任意数量的工厂模式,您可以尝试一种更高级的工厂模式。这真的取决于上下文是什么,你实际上想要做什么,以及练习的目的是什么。

回答by Makoto

Since you're working with a large number of objects, you would be well served placing them in some sort of collection, like an ArrayList.

由于您正在处理大量对象,因此最好将它们放在某种集合中,例如 ArrayList。

List<Counter> counters = new ArrayList<Counter>();

Insert all of your counters into there using the .add()method. Then, you can author your resetCounters()method in this manner:

使用该.add()方法将所有计数器插入那里。然后,您可以resetCounters()以这种方式编写您的方法:

public static void resetCounters(List<Counter> counters) {
    for(Counter c: counters) {
        // perform some action to reset the counters, as described by you
    }
}

回答by Kumar Vivek Mitra

1.First of all there is not need to Initialize a Random nos as an instance variable,just have a Object Reference Varaible, as you are already initializing it in the Constructor.

1.首先不需要初始化一个随机数作为实例变量,只要有一个对象引用变量,因为你已经在构造函数中初始化了它。

eg:

例如:

Random number;

2.Create an ArrayList and store all the Counter objects.

2.创建一个 ArrayList 并存储所有 Counter 对象。

ArrayList<Counter> arr = new ArrayList<Counter>();

3.Add each counter object in to the ArrayList.

3.将每个计数器对象添加到 ArrayList 中。

4.Make reset function Non-static..there is no need for it to be static.

4.使复位功能非静态..不需要它是静态的。

5.Iterate and reset...

5.迭代和重置...

for (Counter c : arr){

      c.reset();
    }

6.In reset() do the following..

6.在 reset() 中执行以下操作...

public void reset(){

         this.number = 0;

     }

回答by GETah

The easiest and elegant way of achieving what you want is keeping a reference to all created objects somewhere, in a factory for example and resetting them when needed.

实现您想要的最简单和优雅的方法是在某处保留对所有创建对象的引用,例如在工厂中,并在需要时重置它们。

public class CounterFactory{
      private List<Counter> counters = new ArrayList<Counter>();

      public Counter createCounter(){
          Counter c = new Counter();
          counters.add(c);
          return c;
      }
      public void resetCounters(){
          for(Counter c : counters) c.setNumber(new Random());
      }
}

And in the main method, use it this way:

在 main 方法中,这样使用它:

public static void main(String[] args) 
{
    CounterFactory f = new CounterFactory();
    Counter counter1 = f.createCounter();
    Counter counter2 = f.createCounter();
    Counter counter3 = f.createCounter();
    Counter counter4 = f.createCounter();
    Counter counter5 = f.createCounter();

    // Reset all counters
    f.resetCounters();
}