1

I need to change this program to use a array instead of an arraylist. Apparently I need to create an array of objects and cast it to E[] but I don't understand how to do this. Any help is appreciated.

public class GenericStack<E> {
  private java.util.ArrayList<E> list = new java.util.ArrayList<E>();

  public int getSize() {
    return list.size();
  }

  public E peek() {
    return list.get(getSize() - 1);
  }

  public E push(E o) {
    list.add(o);
    return o;
  }

  public E pop() {
    E o = list.get(getSize() - 1);
    list.remove(getSize() - 1);
    return o;
  }

  public boolean isEmpty() {
    return list.isEmpty();
  }
}
dungo
  • 103
  • 1
  • 2
  • 13

6 Answers6

1

Instead of:

private java.util.ArrayList<E> list = new java.util.ArrayList<E>();

use:

private Object[] array = new Object[];

And when you have to return a certain value, cast it to E. For example:

public E get(int i) {
    return (E) array[i];
}

This is necessary because Java does not allow you to create arrays of generic type.

Phoenix
  • 1,553
  • 2
  • 13
  • 29
0

You can use following command to create the array.

private E[] arr;
private int index;

public void initialize() {
    arr = (E[]) new Object[100];
    index = 0;
}

public E push(E o) {
    try {
        arr[index++] = o;
    } catch (Exception e) {
        System.out.println("Array not enough..");
    }
    return o;
}

Using this you can implement other methods as well. index can be used to calculate the size of the stack.

In above example, an error was printed when the array bounds were exceeded. Instead you can copy array into another variable when index == arr.length - 1. You can use following function to copy the array..

private void copyArray() {
    E[] tem = (E[]) new Object[arr.length + 100];
    System.arraycopy(arr, 0, tem, 0, arr.length);
    arr = tem;
}
Ramesh-X
  • 4,853
  • 6
  • 46
  • 67
0

You can initialize a generic array like this:

E[] stack = (E[])new Object[size];

I find a generic stack sample in another question: Generic Stack Array

Community
  • 1
  • 1
Leo Xu
  • 174
  • 3
  • 11
  • Though this code compiles and for this very case works, it has a caveat. `stack` variable will not behave at runtime as array of `E` behaves - it will not throw `ArrayStoreException` for raw objects. Essentially, `Object[]` cast to `E[]` *is not* `E[]`. IMHO, the best solution is to stay at raw `Object[]` internally and instead expose `E`-related interface (as Phoenix suggests) – Vasily Liaskovsky Dec 05 '15 at 02:40
0

Actually what you want to do is a Stack Implementation using an Array.

Generic Stack Implementation With Array

public class GenericStack<E> {
    private int index;
    private E[] array;

    public GenericStack(int size) {
        array = (E[]) new Object[size];
        index = 0;
    }

    public int getSize() {
        return index;
    }

    public int getCapacity() {
        return array.length;
    }

    public E peek() {
        return array[index-1];
    }

    // push MUST be void, it only pushes the value into the stack
    public void push(E o) {
        array[index++] = o;
    }


    public E pop() {
        E o = array[index-1];
        index--;

        return o;
    }

    public boolean isEmpty() {
        return index == 0 ? true : false; 
    }
}

Test Code

public class TestGenericStack {

    public static void main(String[] args) {
        GenericStack<Integer> genStack = new GenericStack<Integer>(10);

        // test size
        System.out.println("Size of the Stack  : " + genStack.getSize());

        // test isEmpty()
        System.out.println("Stack isEmpty      : " + genStack.isEmpty());


        System.out.println("*** Stack push operations ***");

        // test push
        genStack.push(new Integer(10));
        genStack.push(new Integer(20));
        genStack.push(new Integer(30));
        genStack.push(new Integer(15));
        genStack.push(new Integer(99));



        // test isEmpty()
        System.out.println("Stack isEmpty      : " + genStack.isEmpty());

        // test peek
        System.out.println("Top of the Stack   : " + genStack.peek());

        // test size
        System.out.println("Size of the Stack  : " + genStack.getSize());

        // test pop
        System.out.println("Pop from the Stack : " + genStack.pop());

        // test peek
        System.out.println("Top of the Stack   : " + genStack.peek());

        // test size
        System.out.println("Size of the Stack  : " + genStack.getSize());
    }

}

Console Output

Size of the Stack  : 0
Stack isEmpty      : true
*** Stack push operations ***
Stack isEmpty      : false
Top of the Stack   : 99
Size of the Stack  : 5
Pop from the Stack : 99
Top of the Stack   : 15
Size of the Stack  : 4
Levent Divilioglu
  • 11,198
  • 5
  • 59
  • 106
0

Array's can't use generic types because it needs to allocate the memory for the type. Therefore, it needs to know which type it is beforehand. You can use the newInstance() method to convert your stack implemented with ArrayList to an Array. The code will look like this.

public E[] toArray() {

    if (size == 0)
        return null;

    E temp = list.get(0);
    E[] stackArray = (E[]) Array.newInstance(temp.getClass(), size);
    for (int i = 0; i < list.size(); i++) {
        stackArray[i] = list.get(i);
    }
    return (E[]) stackArray;
}
-2

The generics are removed in compilation, thus the Helper.toArray will be compiled into returning an Object[].

For this particular case, I suggest you use List.toArray(E[]).

List<E> list = new ArrayList<E>();
     list.add(...);
     list.add(...);

T[]array = list.toArray(new E[list.size()]);
Madushan Perera
  • 2,568
  • 2
  • 17
  • 36
  • Because Java generics are not reified in Java 8, a compiler error results when you attempt to create an array of a parameterized generic type. Your code will not compile. – scottb Dec 05 '15 at 01:57