programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# comparing vectors

joe weakers
Ranch Hand
Posts: 38
Hi there. My problem is as follows:
The set X is composed of 30 unique elements. I have three vectors, A, B, and C, that hold unique elements from X. In other words A,B, and C are all subsets of set X. The size of A ranges from 1-12 and cannot be 0. The size of b ranges from 0-12 and can be empty. The size of C ranges from 1-12 and cannot be 0. A,B, and C all contain unique elements.
What is the best way (optimal solution) to finding the intersection of A and B and C? Is using vectors not a good option - there are so few elements in each vector does it really make any difference? I was going to rely on the contains(obj) method that is provided by java.util.Vector. Is this too slow to be using?
I should also state that if an element is in A then it is extremely likely to be either B or C or both. I know the query is vague but any help would be appreciated nonetheless. thnaks a lot, Joe.

Ilja Preuss
author
Sheriff
Posts: 14112
Well, the *easiest* solution would be to clone A and use retainAll on the clone with both B and C as arguments. After that, the clone contains only elements that are contained in all three original Vectors.

For *big* sets (say, >10000 elements), it's likely that using HashSets instead of Vectors is significantly faster, *if* the elements implement hashcode() in a reasonable way. For your small number of elements, I don't think it would make a measurable difference. In some cases it might in fact be slower. You will have to try to be sure, though.

David Harkness
Ranch Hand
Posts: 1646
All I could add is a tip on (micro) optimization (I know, it's evil): use ArrayList if you can and don't need synchronization.