简体   繁体   English

如何在java中为泛型类定义整数变量?

[英]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... 而且我得到一堆错误“无法从int转换为T”......并且还在构造函数的数组定义中出错...

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: 您没有说为什么要尝试将所有“int”转换为“T”,但我已经可以说:

  • "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. 您的变量“top”必须是int:无论类型为T,变量top都是索引。
  • 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. 你应该编写构造函数来获取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. 您的top变量用于将索引存储到表示堆栈顶部的数组中。 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 . 因此,在使Stack类具有通用性时,不应将其转换为类型T It should remain an int . 它应该仍然是一个int

The parameter to your constructor, size , must be of type int also. 构造函数的参数size也必须是int类型。 As for creating generic arrays, please refer to How to: generic array creation . 至于创建通用数组,请参考如何:通用数组创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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