[英]Interface and class with generics and Comparable
我在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中有很多错误...
代替
public class Heap <T implements Comparable> implements PriorityQueue<T>
写:
public class Heap<T extends Comparable> implements PriorityQueue<T>
它有效(当然实现继承的方法)。 有关更多信息,请参见此处 。
你很亲密 尝试: public class Heap<T extends Comparable>...
这是有关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());
}
}
没关系,伪造的格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.