Writing contains() for a generic collection

后端 未结 4 1387
北海茫月
北海茫月 2020-12-18 10:42

I\'m writing a skiplist class in java as an excercise. I\'ve written a class called SkipListInternal which contains the actual skiplist. I\'ve also mad

4条回答
  •  庸人自扰
    2020-12-18 11:05

    In order for a sorted set implementation to work, the elements of the set have to have an ordering. This may either be "natural" (i.e., the elements implement Comparable) or "imposed" (by using an explicit Comparator during set construction).

    So, the first thing is, that you'd probably rather use the ordering defined for the set elements (after all, you are implementing a SortedSet!) instead of equals in contains for efficiency. I assume, that you are already using an ordering in your internal SkipListInternal -- how'd you maintain the Sorted in SortedSet given only equals?

    The fact that contains is actually declared as contains(Object key) in the interface is really unfortunate. I'd do, what the TreeMap implementation does (which is the underlying container for TreeSet, the standard SortedSet from the collections framework):

    if (comparator != null)
        return getEntryUsingComparator(key);
    if (key == null)
        throw new NullPointerException();
    Comparable k = (Comparable) key;
    

    i.e., cast, assuming the client application using your collection behaves sanely.

提交回复
热议问题