Java泛型类型-无法将泛型类型用作参数


public class pencil<T> {
private T []a;
public pencil(T[] a) {
this.a=(T[]) a;
}
public void pencil1() {
for (int i = 0;i<a.length;i++) {
if (a[i]== "pen") {
System.out.println("pen");

}
}
}
public class objQueue<T>  {
private T[] queue;
private int frontIndex;
private int backIndex;

@SuppressWarnings("unchecked")
public objQueue() {
T[] Queue1=(T[]) new Object[10];
queue=Queue1;
frontIndex=-1;
backIndex=-1;
}


public void enqueue(T newEntry) {
if (isFull()) {
System.out.println("Queue is full");
}
else {

if(frontIndex== -1) {

frontIndex=0;
}
backIndex =(backIndex+1)% queue.length;

queue[backIndex]= newEntry;
}

}

public class main { 
static objQueue<Object> queue=new  objQueue<Object> ;
static pencil pen=new pencil(queue); //it gives error that The constructor pencil(objQueue<Object>) is undefined 
public static void main(String[] args) {
queue.enqueue("pen")
pen.pencil1();
}

这部分给出了错误静态铅笔笔=新铅笔(队列(//它给出了构造函数笔(objQueue(未定义的错误如何在不给出错误或任何正确编写代码的想法的情况下,将队列写成静态铅笔=新铅笔(队列(?

您感到困惑,因为您对实例及其属性使用了相同的名称queue

pencil存在的唯一构造函数将T[]作为参数,您可以这样使用它。

static objQueue<Object> queue = new objQueue<Object> ;
// You'll need to have a getter added for queue
static pencil pen=new pencil(queue.getQueue()); // or queue.queue

顺便说一句,如果您开始为类名objQueue -> ObjQueuepencil -> Pencil使用camelcase,您也会使代码更符合标准

最新更新