Suppose I implement a sorted collection (a simple example is a Set based on a sorted array.) Consider this (incomplete) implementation:
import java.util.*; public class SortedArraySet<E> extends AbstractSet<E> { @SuppressWarnings("unchecked") public SortedArraySet(Collection<E> source, Comparator<E> comparator) { this.comparator = (Comparator<Object>) comparator; this.array = source.toArray(); Arrays.sort(this.array, this.comparator); } @Override public boolean contains(Object key) { return Arrays.binarySearch(array, key, comparator) >= 0; } private final Object[] array; private final Comparator<Object> comparator; }
Now create a set of integers
Set<Integer> s = new SortedArraySet<Integer>(Arrays.asList(1, 2, 3), null);
And check if it contains specific values:
System.out.println(s.contains(2)); System.out.println(s.contains(42)); System.out.println(s.contains("42"));
The third line above will ClassCastException . Not what I want. I would prefer it to return false (as the HashSet does.)
I can get this behavior by catching the exception and returning false:
@Override public boolean contains(Object key) { try { return Arrays.binarySearch(array, key, comparator) >= 0; } catch (ClassCastException e) { return false; } }
Assuming the source collection is correctly printed, what could go wrong if I do this?
finnw source share