I have a little problem connected with interfaces, classes and generics in Java.
First of all, I have an interface which is meant to represent the idea of Priority Queue:
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();
}
As we know we can implement a priority queue by heap or list. Here's my class of heap:
public class Heap <T implements Comparable> implements PriorityQueue<T>
I want to have an ArrayList which will have elements of type T. I want my heap to be prepared for all types which are comparable (classes which implement interface Comparable). T could be a String, Double, Integer or just my own type (then I know that I have to write a compareTo method...).
How can I do that? I have a lot of errors in my NetBeans...
Instead of
public class Heap <T implements Comparable> implements PriorityQueue<T>
write:
public class Heap<T extends Comparable> implements PriorityQueue<T>
It works (Of course implement inherited methods). See here for more information.
You're pretty close. Try: public class Heap<T extends Comparable>...
This is one of the many weird and, IMO, unfortunate things about Java Generics. You never use the implements keyword inside of the < >, only extends. Here's a JUnit test showing it in action:
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());
}
}
never mind the bogus formatting.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.