Reputation: 2633
I have a short class:
public class Stack {
private int[] data;
private int Top;
Public Stack(int size) {
data = new int[size];
top = -1;
}
public void Push (int value) {
top++;
data[top] = value;
}
public int pop() {
return data[top--];
}
public int top() {
return data[top];
}
And i'm getting bunch of errors "cannot convert from int to T"... And also getting an error in the array definition of the constructor...
This is my code, i'm a beginner please help me to understand this:
public class Stack <T> {
private T[] data;
private T top;
Public Stack(T size) {
data = new T[size];// im getting error here "cannot create a generic array of T...
top = -1; // what should I do with this?
}
public void Push (T value) {
top++; //cannot convert from int to T
data[top] = value; //cannot convert from int to T
}
public T pop() {
return data[top--]; //cannot convert from int to T
}
public T top() {
return data[top]; //cannot convert from int to T
}
Upvotes: 1
Views: 78
Reputation: 447
You did not say why you tried to convert all the "int"s to "T"s, but I can already say:
You can not create a generic array. Instead of giving a size to the constructor, you should write the constructor to take an array of T.
public class Stack<T> {
private final T[] data;
private int top;
public Stack(final T[] data) {
this.data = data;
top = -1;
}
public void Push(final T value) {
top++;
data[top] = value;
}
public T pop() {
return data[top--];
}
public T top() {
return data[top];
}
}
edit: I also added "final" to the field "data" because I always declare "final" everything I can.
Upvotes: 2
Reputation: 178253
Your top
variable is meant to store an index into your array representing the top of the stack. It's not meant to store any actual data; it's just an index. Therefore, when making your Stack
class generic, it should not be converted to type T
. It should remain an int
.
The parameter to your constructor, size
, must be of type int
also. As for creating generic arrays, please refer to How to: generic array creation.
Upvotes: 1