Switch classes in Java?

I want to create a class for heap data structure in Java, allowing users to select minheap or maxheap

@H_ 403_ 8@

The constructor should look like this: @ h_ 403_ 8@

@H_ 403_ 8@

public Heap(String type) {
    if (type.equals("min")) {
        //allow this object only to use methods for MinHeap
    } else {
        //allow this object only to use methods for MaxHeap
    }
}

Please note that the two methods are really different For example, this method is used in maxheaps and will not be implemented in the same way in minheap: @ h_ 403_ 8@

@H_ 403_ 8@

public void maxHeapify(int i,int n) {
       int l = leftPos(i);
       int r = rightPos(i);
       int largest;
       if (l < n && heap.get(l) > heap.get(i)) {
           largest = l;
       } else {
           largest = i;
       }
       if (r < n && heap.get(r) > heap.get(largest)) {
           largest = r;
       }
       if (largest != i) {
           swap(i,largest);
           maxHeapify(largest,n);
        }
    }

I use an array to represent maxheap@ H_ 403_ 8@

Is it possible? Or I should create separate classes for maxheap and minheap; Each has its own specific method? Or do you think I should follow this way: example: @ h_ 403_ 8@

@H_ 403_ 8@

public void getMax() {
      if (type.equals("min")) {
            //use the method for MinHeap
      } else {
           //apply the method for MaxHeap
      }
 }

Change the title of the question freely because I don't know how to ask it @ H_ 403_ 8@

Solution

You should have a heap interface with two implementation classes - minheap and maxheap This is how the collections API is designed For example, the list interface has many implementations, some of which include LinkedList and ArrayList

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>