Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What interface represents a LinkedHashSet with insertion order iteration

Tags:

java

sonarqube

I am being pulled up by Sonar due to the following line of code:

public void setFileNames(LinkedHashSet<String> fileNames) {

With the error message:

Avoid using implementation types like 'LinkedHashSet'; use the interface instead

What is the way around this when I want to represent a non-sorted Set which keeps its insertion order? Do I just use a Set and make it clear that the iteration order will be kept?

The stored data will be serialized using JaxB and the iteration order is essential after deserialization.

(I am aware of and completely understand this)

like image 327
Rich Avatar asked Feb 06 '15 14:02

Rich


1 Answers

There is no such interface as it makes no sense to require this behavior for an input. Code creating a Set might have an intention about the order and choose an appropriate implementation when creating the Set.

But how can the question whether a Set has an insertion order, alphabetical order or an arbitrary, e.g. hash based, order make a difference for a method like setFileNames(Set<String> fileNames)?

Declaring the parameter type as Set gives you the guaranty that there won’t be duplicates which has an impact on the behavior, but the insertion order is a meaningless information (unless the caller makes it meaningful) about the history of the Set.

If you insist on having a method signature setFileNames(LinkedHashSet<String> fileNames), I still can pass in a Set with a meaningless order, e.g. calling
setFileNames(new LinkedHashSet<String>(hashSet)) or a set with lexicographical order, e.g. setFileNames(new LinkedHashSet<String>(treeSet)). Your signature makes it only more complicated.

like image 105
Holger Avatar answered Oct 25 '22 08:10

Holger