简体   繁体   English

具有泛型和可比性的接口和类

[英]Interface and class with generics and Comparable

I have a little problem connected with interfaces, classes and generics in Java. 我在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类型元素的ArrayList。我希望为所有可比较的类型(实现接口Comparable的类)准备堆。 T could be a String, Double, Integer or just my own type (then I know that I have to write a compareTo method...). T可以是String,Double,Integer或我自己的类型(然后,我知道我必须编写一个compareTo方法...)。

How can I do that? 我怎样才能做到这一点? I have a lot of errors in my NetBeans... 我的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. 尝试: public class Heap<T extends Comparable>...这是有关Java泛型的许多怪异且IMO的不幸之一。 You never use the implements keyword inside of the < >, only extends. 您永远不会在<>内使用Implements关键字,而只是扩展。 Here's a JUnit test showing it in action: 这是一个显示实际效果的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());
 }
}

never mind the bogus formatting. 没关系,伪造的格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM