我有一些与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>
我希望有一个ArrayList,它将具有类型为T的元素。我希望我的堆可以为所有可比较的类型(实现接口Comparable的类)做好准备。 T可以是String,Double,Integer或者只是我自己的类型(然后我知道我必须编写compareTo方法......)。
我该怎么做?我的NetBeans中有很多错误......
答案 0 :(得分:0)
而不是
public class Heap <T implements Comparable> implements PriorityQueue<T>
写:
public class Heap<T extends Comparable> implements PriorityQueue<T>
它的工作原理(当然是实现继承的方法)。有关详细信息,请参阅here。
答案 1 :(得分:0)
你非常接近。尝试:public class Heap<T extends Comparable>...
这是关于Java Generics的许多奇怪和IMO不幸的事情之一。你永远不会在&lt;里面使用implements关键字。 &gt;,只是扩展。这是一个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());
}
}
不要介意伪造格式。