java - 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 Foo
s which I then can pass into doSomeStuff()
.
As it would be pretty convenient to have a method create all the Foo
s, 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 Foo
s 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 Foo
s which are from other sources/not created by createFoos()
method as well
解决方案
将那些额外的foo1
并foo2
移到createFoo
s 方法中
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]));
推荐阅读
- angular - clr-datagrid 不是已知元素错误 NG8001
- php - 登录系统的可靠性如何,数据库没有唯一的列和电子邮件可以复制
- javascript - 'this' 如何在函数中使用,是否需要?
- r - r 从包含特定字符串的向量返回 ngram
- python - 查找笛卡尔坐标内所有最近邻的 STDV
- python - 在 venv 中优先考虑私有 pypi 服务器
- r - 如何比较数据框中多个局部最小值之间的值?
- python - 计算零的数量返回错误的结果
- elasticsearch - Elastic 中部分搜索的正确索引
- serialization - 为什么在尝试将 JSON 文件反序列化为哈希图时出现错误(“尾随字符”)?