【问题标题】:Interface and class with generics and Comparable具有泛型和 Comparable 的接口和类
【发布时间】:2014-02-09 20:56:05
【问题描述】:

我在与 Java 中的接口、类和泛型有关时遇到了一点问题。

首先,我有一个接口来代表优先队列的概念:

public interface PriorityQueue<T> {

    // insert object o of class T into priority queue with appropriate element
    public void insert(T o);

    // remove an element with the highest priority
    public T remove();  

}

众所周知,我们可以通过堆或列表来实现优先级队列。这是我的堆类:

public class Heap <T implements Comparable> implements PriorityQueue<T>

我想要一个包含 T 类型元素的 ArrayList。我希望我的堆为所有可比较的类型(实现接口 Comparable 的类)做好准备。 T 可以是 String、Double、Integer 或只是我自己的类型(然后我知道我必须编写一个 compareTo 方法......)。

我该怎么做?我的 NetBeans 中有很多错误...

【问题讨论】:

  • 您还需要与自己可比较的类型&lt;T extends Comparable&lt;? super T&gt;&gt;
  • 好的,但你能解释一下你的想法吗?我使用了public class Heap&lt;T extends Comparable&gt; implements IPriorityQueue&lt;T&gt;,一切似乎都很好。我在 Strings、Integers 和 Doubles 上测试了我的堆,我发现整个堆运行正常。
  • 你使用的是原始类型

标签: java class generics interface


【解决方案1】:

代替

public class Heap <T implements Comparable> implements PriorityQueue<T>

写:

public class Heap<T extends Comparable> implements PriorityQueue<T>

它有效(当然实现继承的方法)。请参阅here 了解更多信息。

【讨论】:

    【解决方案2】:

    你已经很接近了。试试:public class Heap&lt;T extends Comparable&gt;... 这是关于 Java 泛型的许多奇怪且 IMO 不幸的事情之一。您永远不会在 中使用 implements 关键字,只会扩展。这是一个 JUnit 测试,展示了它的实际效果:

    import org.junit.Test;
    import java.util.ArrayList;
    import java.util.List;
    import static org.junit.Assert.*;
    
    public class CalcIEProjectTreeTest {
    public static interface Priority<T> {
        public void insert(T item);
        public T remove();
    }
    
    public static class Heap<T extends Comparable> implements Priority<T> {
        private List<T> storage = new ArrayList<T>();
    
        public void insert(T item){
            storage.add(item);
        }
    
        public T remove() {
            return storage.remove(0);
        }
    }
    
     @Test
     public void testStuff() throws Exception {
        Heap h = new Heap<String>();
        h.insert("testString");
        assertEquals("testString", h.remove());
     }
    }
    

    别介意虚假的格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2011-07-09
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多