【问题标题】:Java Generic Type - could not use generic type as parameter [closed]Java Generic Type - 不能使用泛型类型作为参数[关闭]
【发布时间】:2021-07-01 14:30:46
【问题描述】:
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)未定义的错误 队列如何写成静态铅笔笔=新铅笔(队列),而不给出错误或任何正确编写代码的想法?

【问题讨论】:

  • 如果格式好的话,这个问题真的会好很多
  • 你有一个无参数构造函数和一个接受数组的构造函数。当你传入一个 objQueue 对象时,为什么你期望它知道要做什么?
  • 此代码可疑。其中一些语句肯定不会因为语法错误而编译。不遵循完善的命名约定也不是一个好主意。

标签: java arrays class generics types


【解决方案1】:

您感到困惑是因为您对实例及其属性使用了相同的名称 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 -&gt; ObjQueuepencil -&gt; Pencil,那么您的代码也会更加符合标准

【讨论】:

    猜你喜欢
    • 2021-03-27
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多