在实例化 List的不同方法之间做出决定foo 来自 fooService.getFoos()
如果 fooService.getFoos()
返回 List
。
那么你可以这样写:
List<Foo> fooList = fooService.getFoos();
或者这样:
List<Foo> fooList = new ArrayList(fooService.getFoos());
这两种方法生成的 fooList 是否有显着差异?
If fooService.getFoos()
returns List<Foo>
.
then you can write this:
List<Foo> fooList = fooService.getFoos();
or this:
List<Foo> fooList = new ArrayList(fooService.getFoos());
Is there any significant difference in the resulting fooList
between these two approaches?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的 - 您正在创建一个全新的
List
,其中包含原始列表的元素。您正在内存中复制集合,并从头到尾迭代它。您也没有使用该服务提供的实例,并且无法修改原始实例。最后,您省略了第二个片段中的泛型声明。所以使用第一个选项。
更新:您表示您无权修改原始列表。这实际上是 fooService 的问题,而不是其客户端的问题。如果服务也在您的控制范围内,则返回
Collections.unmodifyingList(originalList)
- 因此客户端将无法执行修改操作(尝试时将抛出异常)Yes - you are creating a completely new
List
, containing the elements of the original one. You are duplicating the collection in memory, and iterating it from start to end. You are also not using instance provided by the service, and you can't modify the original. And finally, you've omitted the generics declaration in the 2nd snippet.So use the first option.
Update: you indicated you are not allowed to modify the original list. This is actually a problem of
fooService
, not of its clients. If the service is also in your control, returnCollections.unmodifiableList(originalList)
- thus clients won't be able to perform modification operations (on attempt an exception will be thrown)第二个并不是一个好主意,因为您省略了通用部分。
但主要问题是调用不必要的代码。您可以查看 ArrayList 代码源,您将看到构造函数中使用的所有操作。如果您只需要一个列表,并且
fooService.getFoos()
返回一个有效的列表,那么您应该坚持使用它。这两个语句的结果或多或少是相同的,除非:
fooService.getFoos()
返回的列表不应被修改(出于任何原因),但您仍然希望修改您这边的列表中的元素(而不影响原始列表)。资源:
ArrayList
The second isn't really a good idea because you omit the generic part.
But the main problem is the unnecessary code which will be called. You can look at the
ArrayList
code source, and you'll see all the operations used in the constructor. If you only need a List, andfooService.getFoos()
returns a valid List, you should stick with it.The result of those two statement will be more or less the same unless:
ArrayList
and cast it, but let's face it, you would have declaredArrayList<Foo>
if it was the case.fooService.getFoos()
shouldn't be modified (for any reason) but you still want modify elements in the List on your side (without affecting the original list).Resources :
ArrayList
我会坚持第一个,因为它比第二个读起来更容易并且更有意义。
I'd stick with the first one just because it reads lots easier and makes much more sense than the second one.
在第二个语句中,它仅返回 List 类型。如果您确定方法返回相同类型的书房,您可以使用第一种类型。
In the second statement it returns only of List type. If you are sure of method returning of same type den you can use firs type.