0

I'm having an ArrayList and I'm removing elemts via arrayList.remove().

List<FooListener> listeners = new ArrayList ();

public void removeListener(FooListener listener) {
    listeners.remove(listener); // critical sonar warning
}

Sonar displays it as critical issue since it might has a performance impact:

This call to "remove()" may be a performance hot spot if the collection is large.

How should this be fixed?

Also I can only "Confirm" this issue in SonarQube and not just set it to something like "Won't Fix". How can it be ignored in irrelevant cases?

Liso
  • 195
  • 5
  • 15
  • 1
    look at different types of List if performance is of concern - https://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist-in-java – Arun P Johny Sep 22 '21 at 06:54
  • I'd emphasize @ArunPJohny's comment *if performance is a concern*. – Matthieu Sep 22 '21 at 06:58
  • "How should this be fixed?" Is `removeIf` an option? Can you show the code? – Andy Turner Sep 22 '21 at 07:48
  • 1
    Oh, I really wouldn't worry about the warning in that case. I really doubt you'll have a "large" number of listeners. – Andy Turner Sep 22 '21 at 08:23
  • 1
    For listeners you might want to use a `Set` then. Its `remove()` method should not trigger the warning (see my edited answer). – Matthieu Sep 22 '21 at 08:43
  • 1
    You can use the `SuppressWarnings` annotations like `@java.lang.SuppressWarnings("squid:S00112")` where `squid:S00112` is a rule id – Arun P Johny Sep 22 '21 at 09:32

1 Answers1

1

Ask yourself how "large" can your collections be. Don't try to micro-optimize too early, it probably isn't worth it.

ArrayList are good on many aspects (random access, memory footprint, ...) but not removing. LinkedList are good for removing (only when using an Iterator though, as noted by @AndyTurner) but not for random access, etc. Choose the appropriate one for your use case.

EDIT: If you're using an ArrayList to hold your listeners, you might want to use a Set instead, which remove() method should not trigger the "critical warning".

Matthieu
  • 2,736
  • 4
  • 57
  • 87
  • I mostly wouldn't want to actually fix it but sonarqube won't let me ignore the issue/set it to won't fix. – Liso Sep 22 '21 at 06:57
  • @Liso, that's interesting because the message says "*may be ... if*" ... but shows it as a "critical" issue? – Matthieu Sep 22 '21 at 07:00
  • yes, it displays it as critical and unlike other issues I'm not able to resolve it as fixed/won't fix or false positive. – Liso Sep 22 '21 at 07:34
  • 1
    "LinkedList are good for removing" it's only good for removing via an Iterator or with `removeIf`. Repeated calls to `List.remove(int)` are inefficient because each one has to walk the list to find that element. – Andy Turner Sep 22 '21 at 07:44
  • @AndyTurner true, I edited to make it clearer. – Matthieu Sep 22 '21 at 08:39