0

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();  
        }
    }
csiz
  • 78
  • 7
  • `Obj` is a generic type; you cannot instantiate a generic type with `new`. – Jacob G. Nov 09 '19 at 16:59
  • Relevant (but maybe outdated): https://stackoverflow.com/questions/7563654/java-generics-constraint-require-default-constructor-like-c-sharp –  Nov 09 '19 at 17:01

1 Answers1

1

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.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305