Search code examples
javavectornew-operator

Trying to modify Java Vector's get() to make new T() if the element is null


I'm Trying to modify Java Vector to raise size if im accessing an element bigger than the vector's size. And to insert a new element if im accessing a not initialized element.

Eclipse throws cannot instantiate the type Obj.

public static class Vec<Obj> extends Vector<Obj> {
      @Override
      public Obj set(int a, Obj b) {
          if (super.size()<=a) super.setSize(a+1);
        return (Obj) super.set(a,b);
      }
      @Override
      public Obj get(int a) {
          if (super.size()<=a) super.setSize(a+1);
          if (super.get(a)==null) super.insertElementAt(  new Obj() , a);
        return (Obj) super.get(a);
      }
      public Vec () {
            super();  
        }
    }

Solution

  • There is no guarantee that T has a no-args constructor. Also, people like to use interfaces, so there's a good chance T wont be concrete.

    So, supply an abstract factory to the construction of your Vec. A suitable type is java.util.function.Supplier<T>.

      private final Supplier<T> dflt;
      public Vec(Supplier<T> dflt) {
          super(); 
          this.dflt = Objectes.requireNonNull(dflt); 
      }
      ...
               if (super.get(a)==null) {
                   super.insertElementAt(dflt.get(), a);
               }
    

    Construct as:

        Vec<Donkey> donkeys = new Vec<>(BigDonkey::new);
    

    java.util.Vector methods should be synchronized, although such locking isn't really useful and ArrayList should generally be used instead. Even then, subclassing like this breaks LSP.