本文介绍了潜在的bug使用由集合本身调用的removeAll()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 在使用Sonar的代码审查期间,以下代码已被检测为错误代码: ArrayList< String& ops = new ArrayList< String>(); ops.add(test); ops.removeAll(ops); Sonar抱怨自己上的集合调用的removeAll。 我同意这是丑陋的,但是这会引入bug吗? 注意:这不是我的代码, p> 解决方案问题是 ConcurrentModificationException ,或列表损坏或无限循环,或者无法删除条目或类似情况。 ArrayList ,特别是在Oracle的JDK8中, 这是否意味着该代码是正常的? 代码: 依靠执行列表的 removeAll 来处理一个非常奇怪的用例 b $ b 阅读和理解不必要的复杂,因而造成维护问题 做不必要的工作, 你在这里说的是上下文代码审查。我会标记它,并与作者谈谈为什么他们使用它,并解释为什么 ops.clear(); 或 ops = new ArrayList< String>(); (根据上下文)几乎肯定是一个更好的选择,从可靠性,维护和(非常小)性能角度来看。 During a code review using Sonar , the following code has been detected as a bad one:ArrayList<String> ops = new ArrayList<String>();ops.add("test");ops.removeAll(ops);Sonar is complaining about the removeAll on called by the collection on itself.I agree that it's ugly but can this introduce bugs?NB: This is not my code , I'm reviewing it . 解决方案 The issue is whether a ConcurrentModificationException, or list corruption, or endless looping, or failure to remove entries, or similar may result.ArrayList, specifically, in Oracle's JDK8, seems to be written such that those issues won't occur.Does that mean that that code is okay, then?No, it's not okay.That code:Relies on the implementation of the list's removeAll to be smart enough to handle a very strange use-caseIs unnecessarily complex to read and understand, thus creating maintenance issuesIs doing unnecessary work, thus taking longer to do its job than it needs to (not that this is likely to be a big deal)You said this in in the context of code review. I'd flag it and talk with the author about why they used it, and explain why ops.clear(); or ops = new ArrayList<String>(); (depending on context) would almost certainly be a better choice, from a reliability, maintenance, and (very minor) performance perspective. 这篇关于潜在的bug使用由集合本身调用的removeAll()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-31 12:14