Is there a standard Java List implementation that doesn't allow adding null to it?

前端 未结 7 1868
傲寒
傲寒 2020-12-09 02:31

Say I have a List and I know that I never want to add null to it. If I am adding null to it, it means I\'m making a mistake. So every time I would

7条回答
  •  天命终不由人
    2020-12-09 03:11

    Although this problem sort of yells "delegate", it's much easier with subclassing since you intend to inherit almost all the same functionality.

    class MyList extends List {
    
      //Probably need to define the default constructor for the compiler
    
      public add(Object  item) {
        if (item == null) throw SomeException();
        else super.add(item);
      }    
    
      public addAll(Collection c) {
        if (c.contains(null)) throw SomeException();
        else super.addAll(c);
      }
    }
    

提交回复
热议问题