简体   繁体   中英

How to implement a constructor for a generic type

I haven't done much by way of writing my own generic classes, but I'm trying to make my own ArrayStack class and having trouble understanding how to correctly write the constructor.

public class ArrayStack<T> implements List<T> {

   private T[] a;
   private int n;

   public ArrayStack(T[] a) {
      this.a = a;
   }
}

And my main class that uses it:

public class ArrayStackTester {

   public static void main(String[] args) {
      ArrayStack<Integer> numbers = new ArrayStack<Integer>();
   }
}

This produces a compilation error which says that The ArrayStack<Integer> is undefined , so I obviously suspect a problem with the constructor in the ArrayStack class.

I didn't include all the overriden List methods for brevity.

Try defining this no-args constructor first:

public ArrayStack() {
}

Or alternatively, pass along an array of the right type:

Integer[] array = new Integer[100];
ArrayStack<Integer> numbers = new ArrayStack<Integer>(array);

You defined one constructor, which takes a T[] . Then you tried to call a constructor which has no arguments. You need to define the constructor for new ArrayStack<Integer>() to do what you need it to do.

public ArrayStack() {
    // Initialize a (and possibly n) here as appropriate)
}

Is the ArrayStack class compiled?
There is a generic array, which causes troubles
How to create a generic array in Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM