user4232819
user4232819

Reputation:

Switch Between Classes in Java?

I want to create a class for Heap data structure in Java that allows the user to choose either MinHeap or MaxHeap

the constructor should look like this:

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

Note that the methods really differ from between the 2 types. For example this method is used in MaxHeaps and would not be implemented the same way in MinHeap:

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

Is it possible? Or should I make separate classes for MaxHeap and MinHeap; each with its specific methods? or do you think I should follow this way: Example:

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

Feel free to change the title of the question cause I didn't know how exactly to ask it

Upvotes: 3

Views: 1690

Answers (2)

M A
M A

Reputation: 72874

You can implement it with a single class similar to the way java.util.PriorityQueue is implemented. You can switch the priority by passing the appropriate comparator class.

This is similar to the constructor PriorityQueue(int initialCapacity, Comparator<? super E> comparator) as described in the Javadocs:

Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.

Upvotes: 2

Eran
Eran

Reputation: 393936

You should have a Heap interface with two implementing 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.

Upvotes: 5

Related Questions