【问题标题】:How do I add generic items to a generic ArrayList?如何将通用项添加到通用 ArrayList?
【发布时间】:2013-12-30 11:42:00
【问题描述】:

我有一个任务要求我从头开始实现一个通用优先级队列,但是我遇到了一个我认为没有任何意义的错误。

public class PriorityQueue<E> {
     private ArrayList<E> items = new ArrayList<E>(0);
     ...
     public <E extends Comparable<E>> void insert(E newItem){

       if(numOfItems == 0){
          items.add(newItem); //ERROR: The method add(E) in the type ArrayList<E> 
                                       is not applicable for the arguments (E)
          rear++;
          numOfItems++;
       }else{
            //INCOMPLETE
       }
    }
}

【问题讨论】:

    标签: java generics arraylist


    【解决方案1】:
    public <T extends Comparable<E>> void insert(E newItem){
    

    将第一个'E'改为'T',因为类型参数隐藏了原来的'E'

    【讨论】:

    • 为什么要添加一个从不使用的类型参数?
    【解决方案2】:

    你不需要

    <E extends Comparable<E>>
    

    进入他的实例。您已经在类级别声明了它,因此您不需要方法声明中的类型参数。

    你可以声明

     public void insert(E newItem){
    

    然后它会编译。

    【讨论】:

      【解决方案3】:

      在 PriorityQueue 中,所有项目都必须具有可比性。因此,您必须对类本身进行类似的限制

      public class PriorityQueue<E extends Comparable<? super E>> {
          ...
      

      完成此操作后,您需要从方法中删除类型参数,因为它只会隐藏您正确约束的类类型参数。

          public void insert(E newItem) {
          ...
      

      附: 您需要Comparable&lt;? super E&gt;,因为您需要允许所有项目(E)相互比较的最通用约束。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-30
        • 2021-03-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-26
        • 2014-11-11
        相关资源
        最近更新 更多