2

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.

hax0r_n_code
  • 5,332
  • 11
  • 55
  • 95
  • 2
    You need to define a no-args constructor, if you want to use one. – Alexis C. Jun 28 '15 at 21:12
  • Your only constructor `public ArrayStack(T[] a) {` expects `T[]` array, which in your case is `Integer[]`. Where is this array? – Pshemo Jun 28 '15 at 21:13
  • classic compilation-error. the actual problem is way simpler: the constructor `ArrayStack()` isn't defined. You only defined the constructor `ArrayStack(T[])` – Paul Jun 28 '15 at 21:13
  • Thanks @Paul I missed the simplicity there because of my confusion with properly writing the constructor with defining the generics – hax0r_n_code Jun 28 '15 at 21:15

3 Answers3

3

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);
Óscar López
  • 215,818
  • 33
  • 288
  • 367
  • I guess my confusion is with the generics. The constructor doesn't need to match the class definition? `public ArrayStack() {}` – hax0r_n_code Jun 28 '15 at 21:14
  • 1
    @inquisitor you're calling a no-args constructor, hence you need to define one first. It has nothing to do with generics. – Óscar López Jun 28 '15 at 21:14
  • 1
    @ÓscarLópez thanks and I see that now. I was confused because of the syntax of how a generic class is defined. I thought the constructor definition had to match that. My missing the args was a separate but important issue. Appreciate the help! – hax0r_n_code Jun 28 '15 at 21:18
2

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)
}
Silvio Mayolo
  • 24,199
  • 3
  • 34
  • 65
1

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

Community
  • 1
  • 1
maskacovnik
  • 3,009
  • 5
  • 18
  • 26