简体   繁体   English

最佳实践 - Collection.add()和处理布尔返回值

[英]Best Practice - Collection.add() and handling boolean return value

I did not find anything specific to this question. 我没有找到任何针对这个问题的具体内容。 I have just started working with NetBeans and it thew a 'warning' about a Manual collection add loop: 我刚刚开始使用NetBeans,它是关于手动集合添加循环的“警告”:

for(String str : strings){ list.add(str) }

Net Beans really wanted me to handle the boolean return value from the collection addition: Net Beans真的希望我处理集合添加中的布尔返回值:

for(String str : strings){ boolean add = list.add(str) }

I have never really considered if not storing/handling the return of a collection.add() method as faulty or negligent. 我从来没有真正考虑过是否存储/处理collection.add()方法的返回错误或疏忽。 I've seen it regularly to simply ignore the return value since it may not be valuable. 我经常看到它只是忽略了返回值,因为它可能没有价值。 Is this incorrect? 这是不正确的? What are the ramifications of not handling the return boolean value? 不处理返回布尔值的后果是什么? Or is this just an IDE thing? 或者这只是一个IDE的东西?

Thanks all. 谢谢大家。

The warning is not about ignoring the return value of Collection.add but instead about manually looping through an array and adding to a collection. 警告不是忽略Collection.add的返回值,而是关于手动循环数组并添加到集合。 NetBeans really does not like manual array copies and prefers you use an API method to do the copying. NetBeans真的不喜欢手动数组副本,并且更喜欢使用API​​方法进行复制。

In your case that would be list.addAll( Arrays.asList( strings ) ) . 在你的情况下,将是list.addAll( Arrays.asList( strings ) )

It is the IDE warning to tell you, that the return value not used. IDE警告告诉您,未使用返回值。 You can close this warning in the setting. 您可以在设置中关闭此警告。

Note: If you need to test the item was added or not in some special cases, then you can use this returned boolean value, otherwise you can ignore it. 注意:如果您需要在某些特殊情况下测试是否添加了项目,那么您可以使用此返回的boolean值,否则您可以忽略它。

put @SuppressWarnings({"unchecked", "null", "unused"}) it's funtion Eg: 把@SuppressWarnings({“unchecked”,“null”,“unused”})放在它的功能例如:

@SuppressWarnings({"unchecked", "null", "unused"})
private void myfuntion() {
   ...
   for(String str : strings){ list.add(str); }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM