未指定哪个列表实现
有疑问:
List<String> elements = new ArrayList<String>();
elements = elementDao.findElementsById(elementId);
我对考虑将其更改为
List<String> elements;
elements = elementDao.findElementsById(elementId);
(我将 DAO 与 Hibernate 一起使用)
这会导致任何错误或异常(事实上我没有指定应返回哪个 List 实现)?
I have a doubt considering changing this :
List<String> elements = new ArrayList<String>();
elements = elementDao.findElementsById(elementId);
to
List<String> elements;
elements = elementDao.findElementsById(elementId);
(I'm using DAO with Hibernate)
Can this cause any errors or exceptions (the fact that i'm not specifying which List implementation should be returned) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个创建了一个新的数组列表,没有任何作用。创建的列表只是必须收集的垃圾。
第二个更好,但应该简化为
您似乎认为赋值运算符可以用于填充调用者创建的列表。事实并非如此。赋值运算符仅获取对 DAO 创建的列表的引用(可以是任何类型的列表),并将该引用分配给变量。
The first one creates a new arraylist for nothing. The created list is just garbage that has to be collected.
The second one is better, but should be reduced to
You seem to be thinking that the assignment operator could be used to fill a list created by the caller. This is not the case. the assignment operator just takes the reference to the list created by the DAO (and which could be any kind of List), and assigns this reference to the variable.
您可以安全地更改它,因为:
创建一个新的 ArrayList 并将其分配给 elements,然后
丢弃原始的 ArrayList(并将其标记为垃圾收集)并将在
elementDao
内创建的List
分配给它,因此第二种方法同样安全且更高效。You can safely change it because:
creates a new
ArrayList
and assigns it toelements
, thenthrows the original
ArrayList
away (and marks it to be garbage collected) and assignelements
to it theList
created insideelementDao
, so the second approach is just as safe and more efficient.