Switching between classes in Java?
I want to create a class for a heap data structure in Java that allows the user to choose 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 do differ from the two types. For example, this method is used in MaxHeaps and will not be implemented in 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 am using an array to represent MaxHeap.
Is it possible? Or should I make separate classes for MaxHeap and MinHeap; each with their own specific methods? or do you think I should follow this example: 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, because I didn't know exactly how to ask it
You can implement it with a single class similar to the way java.util.PriorityQueue
. 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 cardinality that orders its elements according to the specified comparator.
source to share