问题描述
我有以下情况:
public ArrayList<A> getMethods(){
return b.c.test();
}
所以,我的问题是b.c.test()
返回一个以Optional<A>
作为返回类型的值.但是我需要返回一个ArrayList<A>
.
So, my problem is that b.c.test()
returns a value with Optional<A>
as return type. But I need to return an ArrayList<A>
.
因此,我尝试将其强制转换并重写为:
So, I tried to cast it and rewrite it to :
public ArrayList<A> getMethods(){
return (ArrayList<A>)b.c.test();
}
但是Eclipse表示不可能从Optional<A>
转换为ArrayList<A>
.
But Eclipse says that such a cast from Optional<A>
to ArrayList<A>
is not possible.
我该如何解决这个问题?
How can I solve this problem?
推荐答案
我假设您的预期语义是如果存在该值,则返回一个包含单个项目的列表,否则返回一个空列表."在这种情况下,我会建议以下内容:
I am presuming your intended semantic is 'if the value is present return a list with a single item, otherwise return an empty list.' In that case I would suggest something like the following:
ArrayList<A> result = new ArrayList<>();
b.c.test().ifPresent(result::add);
return result;
但是,我建议您的返回类型应为List<A>
而不是ArrayList<A>
,因为这使您可以在不更改调用方的情况下更改列表的类型.如果不存在可选值,它还允许您返回Collections.EMPTY_LIST
,这比创建不必要的ArrayList
更为有效.
However I would suggest your return type should be List<A>
rather than ArrayList<A>
as that gives you the opportunity to change the type of list without changing the callers. It would also allow you to return Collections.EMPTY_LIST
if the optional value is not present which is more efficient than creating an unnecessary ArrayList
.
更新:Java 9现在有一个更简单的选项:
Update: there's now an easier option with Java 9:
b.c.test().stream().collect(Collectors.toList());
这篇关于从Optional<>到ArrayList<>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!