-1
**//generic class** 
 public class Stack <T> {
         *instance variables below*
        private int top=1;
    
        private T[] stackArray;
    
        private int stackSize;
        *constructor*
        public Stack(int size){
    
            
            **this is where im getting the warning "[unchecked] unchecked cast"**
            this.stackArray = (T[] )new Object[size];
         
    
            *stack pointer and the stack size*
            top=-1;
            this.stackSize=size;
    
        }
akarnokd
  • 69,132
  • 14
  • 157
  • 192
Ghani Elk
  • 1
  • 1
  • This response by dimo414 and the comments gives quite a nice description of this scenario: https://stackoverflow.com/a/2924453/5294591 – Will Moffat Jun 16 '22 at 21:25
  • You are getting an unchecked cast warning because the cast `(T[])` cannot be checked at runtime, because the class instance doesn't know what `T` is at runtime. – newacct Jun 25 '22 at 06:52

1 Answers1

0

You can't create an Generic Array of T[]. There are some takes you could make:

For example making T[] an Object[]

 public class Stack <T> {
         *instance variables below*
        private int top=1;
    
        private Object[] stackArray;
    
        private int stackSize;
        *constructor*
        public Stack(int size){
    
            this.stackArray = new Object[size];
         
    
            *stack pointer and the stack size*
            top=-1;
            this.stackSize=size;
    
        }

You would need to do (T)stackArray[i] on your get operations though for more detail look into the implementation of java.lang.ArrayList.

Else you could require a "sample" of an T[] array in your constructor and then construct an new of that type:

public Stack(T[] array, int size){
    
            this.stackArray = (T[]) Array.newInstance(array.getClass().getComponentType(), size);
         
    
            *stack pointer and the stack size*
            top=-1;
            this.stackSize=size;
    
        }

Alternatively you could use a generator method:

public Stack(IntFunction<T[]> generator, int size){
    
            this.stackArray = generator.apply(size);
         
    
            *stack pointer and the stack size*
            top=-1;
            this.stackSize=size;
    
        }

This would be called like this:

Stack<String> stack = new Stack<>(String[]::new,10);

this works because you can think of an array constructor as a method that takes an int as it's parameter and returns an array of T[] (public static <T> T[] arrayConstructor(int size){...})

Bonus tip you can cache any constructor with this method as long as you have a functional interface that matches the constructor:

@FunctionalInterface
public interface Constructor {
Foo ctor(Bar b, int i, String s);
}

class Foo {

   public Foo(Bar b, int i, String s) {...}
}

Constructor ctor = Foo::new; // <- constructor of Foo that can be passed as a variable.
RedCrafter LP
  • 174
  • 1
  • 8