Writing contains() for a generic collection

后端 未结 4 1363
北海茫月
北海茫月 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 10:57

    Since the contains() is from java.util.Collection, We are supposed to follow the Collection.contains() contract. Because throwing ClassCastException is an optional behavior, it's correct to return false in your code when cast fails. So I think your implementation comply with the contract.

            /**
             * Returns true if this collection contains the specified element.
             * More formally, returns true if and only if this collection
             * contains at least one element e such that
             * (o==null ? e==null : o.equals(e)).
             *
             * @param o element whose presence in this collection is to be tested
             * @return true if this collection contains the specified
             *         element
             * @throws ClassCastException if the type of the specified element
             *         is incompatible with this collection (optional)
             * @throws NullPointerException if the specified element is null and this
             *         collection does not permit null elements (optional)
             */
             boolean contains(Object o);
    

提交回复
热议问题