Writing contains() for a generic collection

后端 未结 4 1390
北海茫月
北海茫月 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:21

    @Joaschim comment is correct for standard collections, however if you want a checked collection I suggest you check what can be added, and not optimise for the lookups of invalid types (unless you want to throw an Exception) You can do something like.

    public class SkipListSet implements SortedSet{
       private final Class eClass;
       private final SkipListInternal skiplist;
    
       ...
       public boolean add(Object o) {
           if(!eClass.isInstanceOf(o))
        // OR
           if(eClass != o.getClass())
               throw new IllegalArgumentException("Type "+o.getClass()+" is not a "+eClass);
           skiplist.add(o);
       }
    
       public boolean contains(Object o){
           // if (!(o instanceof E)) return false; // don't need to optmise for this.
           return skiplist.find((E) o) != null;
       }
    
       ...
    
    }
    

    BTW: Java has a builtin thread safe ConcurrentSkipListSet and ConcurrentSkipListMap You might find it interesting to read the source for this. ;)

提交回复
热议问题