0

I have a generic class I'd like to convert from C# to Java. The class starts off this way:

   public class StackImplementationUsingDynamicArray<T>
    {
        private T[] _array = new T[10];
    }

I can't seem to get the equivalent Java code for the declaration. This code at least compiles (with a warning) but throws a runtime exception:

   public class StackImplementationUsingDynamicArray<T>
    {
        private T[] _array = (T[])Array.newInstance (StackImplementationUsingDynamicArray.class, 10);
    }

Is it possible to do this in Java? What should the code be? Thanks in advance for any pointers.

Red Wei
  • 799
  • 4
  • 19
ldl01031
  • 9
  • 2
  • `Deque likeThis = new ArrayDeque<>();` – Elliott Frisch Mar 14 '18 at 01:53
  • @ElliottFrisch Why `new ArrayDeque<>()` and not `new ArrayList<>(10)`? Since it's to be used as a replacement for an array, wouldn't you need the `get(int)` method of `List`? – Andreas Mar 14 '18 at 02:25
  • 1
    @Andreas Sorry, I would replace `StackImplementationUsingDynamicArray` with an `ArrayDeque`. Since that's what it (basically) is. From the [`Deque`](https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html) Javadoc, *Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy Stack class. When a deque is used as a stack, elements are pushed and popped from the beginning of the deque.* – Elliott Frisch Mar 14 '18 at 02:36
  • Thanks for the thoughts. This is actually just 'practice' as I work on learning Java. I had some earlier C# code I had written as practice for interviews - and this was one of the routines. I had several implementations of a stack - a dynamic array being just one. ArrayList would have made it too easy :) And I did see the answers to similar questions but - I was missing something. Erwin's answer made it crystal clear and I was able to finish. Turns out that Java is just different enough from C# to keep me on my toes... – ldl01031 Mar 14 '18 at 05:40

1 Answers1

1

Yes - but you need to pass the class object of the actual type to the constructor of the class:

public class StackImplementationUsingDynamicArray<T>
{
    private T[] _array;
    public StackImplementationUsingDynamicArray(Class<T> clazz) {
        _array = (T[]) Array.newInstance(clazz, 10);
    }

Which you can then use like this:

StackImplementationUsingDynamicArray<String> a =
        new StackImplementationUsingDynamicArray<>(String.class);
Erwin Bolwidt
  • 28,093
  • 15
  • 46
  • 70