简体   繁体   English

类型参数原因错误

[英]Type parameter cause error

I have this class as follows :- 我的课程如下:

import java.util.*;
public class QueueTest<T>{

    Queue<T> q = new LinkedList<T>();
    int capacity;

    public QueueTest(int capacity){
        this.capacity = capacity;
    }

    **public <T> void put(T item) throws InterruptedException**{
        while(q.size()== capacity){
            System.out.println("Now Queue is full and i will wait");
            wait();
        }
        q.add(item);
        System.out.println("I added : "+item);
        notify();
    }

    public T got() throws InterruptedException{
        while(q.isEmpty()){
            System.out.println("Now Queue is empty and i will wait ");
            wait();
        }
        T item = q.remove();
        System.out.println("I got : "+item);
        notify();
        return item;
    }
}

the declaration of method put() cause this error ?? 方法put()的声明导致此错误?

QueueTest.java:17: error: no suitable method found for add(T#1)
                q.add(item);

and when I remove T , the class compiled without errors, but I don't know why ??? 当我删除T时 ,该类编译没有错误,但是我不知道为什么?

Get rid of the T in 摆脱T in

public <T> void put(T item) throws InterruptedException{
        ^

If you leave it, you are declaring a different type variable that is shadowing your class' type variable T . 如果您不使用它,那么您将声明一个不同的类型变量,该变量正在遮盖类的类型变量T You can bind a different type to this one, so the compiler cannot guarantee that it will be the same as the one bound to the Queue . 您可以将另一种类型绑定到该类型,因此编译器不能保证它与绑定到Queue You seem to want to use the same type variable as the one the in the class declaration. 您似乎想使用与类声明中相同的类型变量。

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

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