使用 Abstract 类 构造堆

Using Abstract Classes to Construct a Heap

对于抽象 classes 代码的实际实现及其意义,我有点困惑。

我为最大堆编写了代码,我想基于它做一个抽象 class 这样我就可以有一个堆的一般轮廓,而不仅仅是 "Max" 堆.

我的 MaxHeap 主体如下所示:

public class MaxHeap {

    // A class for nodes, just has 3 fields, lchild, rchild, and value
    private HeapNode top;
    private List<HeapNode> heap;

    public MaxHeap() {
        this.top = null;
        this.heap = new ArrayList<>();
    }

    //I won't go into the guts of these methods, but will explain

    //Displays the heap like [1,2,3,4,5,...]
    public void display() {...}

    //Adds a new HeapNode to the end of heap, if empty sets to top
    public void add(int value) {...}

    //Deletes a HeapNode at index pos
    public void delete(int pos) {...}

    //Swaps 2 Nodes within the heap
    protected void swap(int pos, int otherPos) {...}

    //// These are the methods that actually differ depending on the
    //// type of heap (maxheap, minheap, etc) so I would assume they
    //// would be abstract methods if writing an abstract class?
    |
    |
    V

    //Called within add method, heapifys the heap after adding a new Node
    protected void addHeapify(int pos) {...}

    //Called within delete method, heapifys the heap after deleted Node
    protected void deleteHeapify(int pos) {...}

    //Called within deleteHeapify for "if (pos==0) {...}", delete max Node
    protected deleteExtremum() {...}
}

我的问题反映了我将如何在更抽象的层面上实现它?我想将我的编码提升到一个新的水平,并且需要理解这一点。我会做这样的摘要吗class?

public abstract class Heap {

private HeapNode top;
private List<HeapNode> heap;

public Heap() {...}

// **************
// public methods
// **************

public void display() {...}
public void add(int value) {...}
public void delete(int pos) {...}

// ******************
// non-public methods
// ******************

protected void swap(int pos, int otherPos) {...}

// ****************
// abstract methods
// ****************

protected abstract void addHeapify(int pos);
protected abstract void deleteHeapify(int pos);
protected abstract void deleteExtremum();

}

了解 "abstract-ify" 原文 class 的正确方法对我有很大帮助。

在抽象中添加字段和构造函数是否正确 class,即使添加、删除、交换和显示在不同堆之间不会改变,这些方法也应该是抽象的吗?

我也想知道我是否应该使用接口来代替,但它似乎是一个更严格的抽象class,我将无法定义添加、删除、交换和显示.

摘要 class 是几个具体 class 的概括。它用于共享通用功能和数据。因为它是抽象的,所以如果没有一些定制就不能实例化(使用)。如果 class 可以按原样使用,它就不是抽象的。

如果你需要针对接口的抽象class,重要的一点是抽象是否包含数据。您可以使用带有数据字段的抽象 class 和仅抽象方法。

当您的通用功能需要某些特定于继承者的数据或处理时,应使用抽象方法。就像如果您的 add 方法出于某种原因需要调用 addHeapify,但不关心它是通过哪种方式实现的。

如果你需要所有的后代都有一些方法,但它不用于公共功能,使用接口是明智的,因为接口定义了 class 应该如何表现,但没有定义哪个它包含的数据。因此,您可以对包含不同数据的两个 classes 进行抽象。 在 Java 8 中,您可以直接在接口中实现 default methods(以前不可能),因此只有当您有公共数据要存储在其中时,才需要抽象 class。

请记住,其他算法可以使用对抽象 classes 或接口的引用来调用您的算法,而无需知道引用背后的实现是什么。这主要用于使代码可变,因为您可以在不更改客户端代码的情况下替换接口或抽象 class 的任何实现。