Search code examples
javavariadic-functions

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!


Solution

  • You can use varargs

    private List<Object> objects;
    
    public void generate(Object... objects) {
        this.objects = Arrays.asList(objects);
    }