0

So I have a basic stack implementation here using an interface in Java and I had a couple of questions on how all this works,

public class ArrayStack<T> implements ArrayStackADT<T> {
private T[] ArrayStack;
private int top;

public ArrayStack() {
    ArrayStack = (T[]) new Object[20];
}

So I do understand that this line ArrayStack = (T[]) new Object[20]; creates an array implementation of a Stack with size 20 but I'm confused about what (T[]) and 'new Object' do and why they are required there? Could anyone describe it in Layman terms?

CosmicCat
  • 612
  • 9
  • 19
  • Possible duplicate of [what's T\[\] object?](https://stackoverflow.com/questions/9237029/whats-t-object) – Mark Melgo Feb 20 '19 at 07:52
  • https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java – Eran Feb 20 '19 at 07:52
  • Because before the runtime compiler does not know what is the T,because we set it like ArrayStack. Thus,when you want to create the array of generic types,you should make it with Object class which all classes extend this class.So,this will pass compilation because T extends Object no matter what T is. – Y.Kakdas Feb 20 '19 at 08:30
  • As a side note, please follow some naming conventions: class names starting with an uppercase letter, method/variable starting with a lowercase letter. Especially if you want to name a class field the same way as the class itself. – Amongalen Feb 20 '19 at 08:40

0 Answers0