Home > database >  Is there a way to loop execute a method while passing a different instance of a class to it each tim
Is there a way to loop execute a method while passing a different instance of a class to it each tim

Time:08-13

My current code looks something like this:

public void myMethod()
{
   instance1.myPanel.setVisible();
   instance2.myPanel.setVisible();
   instance3.myPanel.setVisible();
   instance4.myPanel.setVisible();
   //A bunch more
   instance57.myPanel.setVisible();  
}

Is there a ways to shorten it? The Code below obviously doesn't work but gives you an idea of what I'm trying to do:

public void myMethod2(myClass instance1)
{
   instance1.myPanel.setVisible();
}

int i = 1;
while(i <= 57)
{
   myMethod2("instance"   i);
   i  
}

CodePudding user response:

In practice, this kind of problem is normally handled using some sort of collection, and its use will often fit naturally into the initialization of a program with a large number of objects. Rather than hand-writing the creation of 57 similar objects, one line at a time, you would create them in a loop, adding them to a collection as you do so.

A List implementation like ArrayList would be a good choice here, or one could simply use an array.

With a List:

/* During initialization of your program somewhere. */
List<MyClass> instances = new ArrayList<>();
for (int i = 0; i < 57;   i) {
  instances.add(new MyClass());
}

...

/* Later when you need to invoke a method: */
instances.forEach(instance -> instance.myPanel.setVisible());

CodePudding user response:

You can build a list of your vars and just go through them:

List<ClassType> list = Arrays.asList( obj1, ob2, obj3 );
list.forEach( instance -> instance.myPanel.setVisible() );
  •  Tags:  
  • java
  • Related