简体   繁体   中英

How to define integer variables for a generic class in java?

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

   }

You did not say why you tried to convert all the "int"s to "T"s, but I can already say:

  • "public" (visibility of the constructor) should be without the capital.
  • Your variable "top" must be an int : whatever the type T, the variable top is an index.
  • 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM