首页 > 解决方案 > Java method return type acceptable for method argument [...]

问题描述

Following method signature:

public void doSomeStuff(Foo ... names){

}

now assume that I have a List<String> names which I want to convert to Foos which I then can pass into doSomeStuff().

As it would be pretty convenient to have a method create all the Foos, I thought about implementing a method as following:

public Foo[] createFoos(List<String> names){
    Foo[] foos = new Foo[names.size()];
    //create all the Foo's and pass them into array
    return foos;
}

in the end I would like to have this kind of code (I have a few Foos from other sources available or they do require special treatment):

doSomeStuff(foo1, foo2, createFoos(names));

So the question is, is it possible to implement a method (createFoos()) which returns an object that is accepted by a method with the Foo ... names signature, and if so, how would one go about it?


I am sorry if this is a duplicate, I couldn't find anything regarding this topic

EDIT:

As I just realized, the requirements are a bit different. Sorry about the confusion. Updated the method call.

The crucial part is that I need to pass in a few Foos which are from other sources/not created by createFoos() method as well

标签: java

解决方案


将那些额外的foo1foo2移到createFoos 方法中

public Foo[] createFoos(List<String> names, Foo... extraFoos){
    Foo[] foos = new Foo[names.size() + extraFoos.length];
    //create all the Foo's and pass them into array
    return foos;
}

像这样称呼它

doSomeStuff(createFoos(names, foo1, foo2));

或者,返回一个列表,然后附加到它,最后将它变成一个数组。

public List<Foo> createFoos(List<String> names){
    List<Foo> foos = new ArrayList<>();
    //create all the Foo's and pass them into array
    return foos;
}

用法:

List<Foo> foos = createFoos(names);
foos.add(foo1);
foos.add(foo2);
doSomeStuff(foos.toArray(new Foo[0]));

推荐阅读