简体   繁体   English

在Java中将泛型与抽象数据类型一起使用

[英]Using Generics with Abstract Data Types in Java

For a CS class I need to solve an assigned problem using three data structures: Queue, PriorityQueue, and Stack. 对于CS类,我需要使用三个数据结构来解决分配的问题:Queue,PriorityQueue和Stack。 I wanted to write a single solution to the problem using an abstract data structure. 我想使用抽象数据结构为该问题写一个解决方案。 I would implement the ADT with a wrapper class of each required data type. 我将使用每种所需数据类型的包装器类来实现ADT。 This is what I have so far: 这是我到目前为止:

An interface called Method : 一个名为Method的接口:

public interface Method<E> {

    public abstract void add(E data);
    public abstract E remove();
    public abstract E peek();
    public abstract Iterator<E> Iterator();
}

And three wrapper classes that implement the interface. 还有三个实现该接口的包装器类。 I called them QueueMethod, StackMethod, and PriorityQueueMethod. 我称它们为QueueMethod,StackMethod和PriorityQueueMethod。 I'm having some trouble implementing the interface though. 我在实现接口时遇到了一些麻烦。 This is a start for the implementation that gives the error "Class is not abstract and does not override abstract method add(java.lang.Object)." 这是实现错误“类不是抽象的,并且不覆盖抽象方法add(java.lang.Object)”的实现的开始。 As far as I can tell the signature of the two add methods are identical. 据我所知,两个添加方法的签名是相同的。

Here's the beginning QueueMethod wrapper class: 这是开始的QueueMethod包装器类:

public class PriorityQueueMethod<T> implements Method {

    PriorityQueue<T> queue;

    public PriorityQueueMethod() {
        queue = new PriorityQueue<T>();
    }

    public void add(T data) {
        queue.offer(data);
    }
}

将泛型添加到要实现的Method类中,如下所示:

public class PriorityQueueMethod<T> implements Method<T> 

Use the generic signature in your implements declaration: 在您的implements声明中使用通用签名:

public class PriorityQueueMethod<T> implements Method<T>

Here's a sample implementation for an ArrayList based solution: 这是基于ArrayList的解决方案的示例实现:

public class ArrayListMethod<T> implements Method<T>{

    private final List<T> inner;

    public ArrayListMethod(){
        inner = new ArrayList<T>();
    }

    public ArrayListMethod(final Collection<T> data){
        inner = new ArrayList<T>(data);
    }

    @Override
    public void add(final T data){
        inner.add(data);
    }

    @Override
    public T remove(){
        return inner.remove(0);
    }

    @Override
    public T peek(){
        return inner.get(0);
    }

    @Override
    public Iterator<T> Iterator(){
        return inner.iterator();
    }
}

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

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