Built-in methods use the standard equals
method to see if two objects are equal; nobody will use your own isSimilar
method.
Fortunately, it is easy to program the logic for calculating the intersection itself: go through the elements in the first list and add it to the intersection if it exists in the second list.
List<YourObject> intersection = new ArrayList<YourObject>(); for (YourObject a: list1) for (YourObject b: list2) { if (a.isSimilarTo(b)) { intersection.add(a); break; } }
Complexity of calculations: if there are n elements in the first list and m elements in the second list, this algorithm makes O (nm) comparisons possible. If the lists have been sorted or another data structure (for example, a hash table) can be used, the complexity can be reduced to O (n + m).
On the other hand, you can create a wrapper class for your objects and which uses the isSimilar method for equality:
final class YourObjectWrapper { YourObject value; public boolean equals(Object o) { return o instanceof YourObjectWrapper ? value.isSimilarTo(((YourObjectWrapper) o).value) : false; }
If you populate your lists with these wrapper objects, you can use built-in methods such as retainAll
.
Joni source share