Faisal
Faisal

Reputation: 324

How to get return type of interface<T>?

im stuck in this problem i tried to correct it but nothing changed..

so first of all "Stack" is an interface and this is the required method

which copy the array stack and return it as new stack, this my code:

public class ArrayStack<Type> implements Stack<Type> {

private int maxSize;
private int top;
private Type [] nodes;

@SuppressWarnings("unchecked")

public ArrayStack(int n){
    maxSize = n ;
    top = -1 ;
    nodes = (Type[]) new Object[n];
}



@SuppressWarnings("unchecked")

public Stack<Type> copy() {

    int n = nodes.length;
    Type[] ns = (Type[]) new Object[n];

    for(int i = 0 ; i < n ; i++){

        ns[i]= nodes[i];
    }



    return ns;
}

so i get a compile error on "return ns;" statement which says:

Type mismatch: cannot convert from Type[] to Stack

i don't know if i wrote the method signature or the new array in a wrong way ..

i will appreciate your help :)

Upvotes: 0

Views: 64

Answers (1)

GhostCat
GhostCat

Reputation: 140427

Here:

Type[] ns

is returned, and should thus be:

Stack<Type>

But an array of T's ... isnt a Stack of T. You have to make up your mind, should the method return an array (then change the signature), or should it return a new Stack instance (in that case, you can't return that ns array!)

As the name copy() implies the later, you probably should:

  • create a new instance of ArrayStack
  • setup the stack of that new Stack with the same content that the original Stack offers ... and then
  • return that new ArrayStack instance.

Upvotes: 3

Related Questions