1

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...

TheOpti
  • 1,641
  • 3
  • 21
  • 38
  • 1
    you also want types which are comparable *to themselves*: `>` – newacct Feb 10 '14 at 08:13
  • OK, but could you explain me your idea? I used `public class Heap implements IPriorityQueue` and everything seems fine. I tested my heap on Strings, Integers and Doubles and I see that the whole heap is working properly. – TheOpti Feb 14 '14 at 15:33
  • you are using a raw type – newacct Feb 14 '14 at 19:17

2 Answers2

0

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.

Community
  • 1
  • 1
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
0

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.

allTwentyQuestions
  • 1,160
  • 7
  • 11