简体   繁体   中英

create a list of objects dynamically depending on method parameters in JAVA

What I have is a method with like this one:

  private objects;

  public generate(ArrayList<Object> objects) {
        this.objects = objects;
    }

so to call it I need first to generate a list of my objects and then pass it to the method

ArrayList<Object> o;
o.add(new Object a());
o.add(new Object b());

generate(o);

is there a way to call my "generate" method passing there all objects as attributes, independent of the count of parameters? like

generate(new Object a(), new Object b(), .. .etc )

thanks!

You can use varargs

private List<Object> objects;

public void generate(Object... objects) {
    this.objects = Arrays.asList(objects);
}

Yes.

public void generate(Object... objects) {
   for (Object myObject : objects) {
       myObjectsArrayList.add(myObject);
   }
}


generate(new Object a(), new Object b());

Simply modify your generate method to use a vararg argument ( variadic arguments ):

    public void generate(Object... objects) {
        this.objects = Arrays.asList(objects);
    }

Quoting from the documentation, which can be found here :

In past releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method.

Fortunately this is no longer necessary. Here's a complete example:

public class MyObjects {
    private List<Object> objects;

    public void generate(Object... objects) {
        this.objects = Arrays.asList(objects);
    }

    public static void main(String[] args) {
        MyObjects h = new MyObjects();

        h.generate(new Object());
        h.generate(new Object(), new Object());
        h.generate(new Object(), new Object(), new Object());

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM