lew-kas
lew-kas

Reputation: 41

How to return generic methods?

I'm doing my homework right now and I stumbled on a, probably pretty easy, 'problem'.

I have to build a stack and I need to complete the following method:

public E top()
    {   
        if(!isEmpty()) {
            /*
             * return top element
             * which would be st[pos-1]
             */
        }
        return null;
    }

I use

//to save elements
private Object[] st;

//for position in array
private int pos = 0;

I tried to return my array, but it tells me "Cannot convert from Object to E". Now I don't know how to continue.

//edit: my constructor

public Stack(int size)
    {
        st = new Object[size];
        //st = new E[size]; doesn't work

    }

Upvotes: 0

Views: 37

Answers (2)

Andy Turner
Andy Turner

Reputation: 140544

You need to cast:

E element = (E) st[pos-1];

You will get an unchecked cast warning, though. This is safe to suppress, provided you ensure that only instances of E are added to the array.

void add(E element) {
  st[pos++] = element;
}

(And that is pretty much what java.util.ArrayList does, btw)

Upvotes: 2

Anas K
Anas K

Reputation: 771

Your Array should be of type E

private E[] st;

Upvotes: 0

Related Questions