I have created a method that takes two Collection<String> as input and copies one to the other.
However, I am not sure if I should check if the collections contain the same elements before I start copying, or if I should just copy regardless. This is the method:
/**
* Copies from one collection to the other. Does not allow empty string.
* Removes duplicates.
* Clears the too Collection first
* @param src
* @param dest
*/
public static void copyStringCollectionAndRemoveDuplicates(Collection<String> src, Collection<String> dest) {
if(src == null || dest == null)
return;
//Is this faster to do? Or should I just comment this block out
if(src.containsAll(dest))
return;
dest.clear();
Set<String> uniqueSet = new LinkedHashSet<String>(src.size());
for(String f : src)
if(!"".equals(f))
uniqueSet.add(f);
dest.addAll(uniqueSet);
}
Maybe it is faster to just remove the
if(src.containsAll(dest))
return;
Because this method will iterate over the entire collection anyways.
I’d say: Remove it! It’s duplicate ‘code’, the Set is doing the same ‘contains()’ operation so there is no need to preprocess it here. Unless you have a huge input collection and a brilliant O(1) test for the containsAll() 😉
The Set is fast enough. It has a O(n) complexity based on the size of the input (one contains() and (maybe) one add() operation for every String) and if the target.containsAll() test fails, contains() is done twice for each String -> less performant.
EDIT
Some pseudo code to visualize my answer
If all source elements are in dest, then contains() is called once for each source element. If all but the last source elements are in dest (worst case), then contains() is called (2n-1) times (n=size of source collection).
But the total number of contains() test with the extra test is always equal or greater then the same code without the extra test.
EDIT 2
Lets assume, we have the following collections:
First, the containsAll test fails, because the empty String in source is not in dest (this is a small design flaw in your code ;)). Then you create an temporary set which will be
{"a", "b", "c"}(empty String and second “c” ignored). Finally you add everthing to dest and assuming, dest is a simple ArrayList, the result is{"a", "b", "a", "b", "c"}. Is that the intention? A shorter alternative: