• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Generic Stack Class

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class GenericStack<E> {
private int top;

private int size = 0;

E[] elements;

GenericStack() {
this(10);
}

GenericStack(int size) {
this.size = size;
top = -1;
elements = (E[]) new Object[size];
}

public <E> void push(E input) {
elements[++top] = input; //Compile time error
}
}

This code gives compile time error saying
Type mismatch: cannot convert from E to E

Could you explain this?

Also when I write the push method as:

public void push(E input) {
elements[++top] = input;
}
In this case there is no error.

What is the difference between the two syntaxes?
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you write the push method as:

public <E> void push(E input)

you are redefining the E type. This E can be a totally different E than the one you used when defining your class. You are actually hiding the type E with the type parameter E (just like an parameter can hide and instance variable)

If you define the method as:

public <F> void push(F input)

you will get the message "cannot convert from F to E", which is more clear...
reply
    Bookmark Topic Watch Topic
  • New Topic