In: Computer Science
I have created a MinHeap program without using arrays. Below is the followup question :
The heap class is a collection. Determine the correct
location in your language’s collection
class hierarchy. Find all methods that you need to implement in
order to add your class in
the language’s collection class hierarchy.
What does this mean and how to implement it?
The heap class is a collection as collection class is used exclusively with static methods that operate on or return collections. It can also inherit the Object class.
Also, We use the PriorityQueue class to implement Heaps in Java. By default Min Heap is implemented by this class. To implement Max Heap, we use Collections.reverseOrder() mwthod
Below is the java code using collections in java for better understanding
// code import java.util.*; class Example { public static void main(String args[]) { // Created empty priority queue PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>(Collections.reverseOrder()); // Add items to the priorityQueue using add() priorityQueue.add(10); priorityQueue.add(30); priorityQueue.add(20); priorityQueue.add(400); // Print the highest priority element System.out.println("Head value using peek function:" + priorityQueue.peek()); // Print all elements System.out.println("The queue elements:"); Iterator iterator = priorityQueue.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); // Remove the top priority element and print the modified priorityQueue using poll() priorityQueue.poll(); System.out.println("After removing an element " + "with poll function:"); Iterator<Integer> itr2 = priorityQueue.iterator(); while (itr2.hasNext()) System.out.println(itr2.next()); // Remove 30 using remove() priorityQueue.remove(30); System.out.println("after removing 30 with" + " remove function:"); Iterator<Integer> iterator1 = priorityQueue.iterator(); while (iterator1.hasNext()) System.out.println(iterator1.next()); // Check if an element is present or not using contains() boolean b = priorityQueue.contains(20); System.out.println("Priority queue contains 20 " + "or not?: " + b); // Get objects from the queue using toArray() in an array and print the array Object[] ar = priorityQueue.toArray(); System.out.println("Value in array: "); for (int j = 0; j < ar.length; j++) System.out.println("Value: " + ar[j].toString()); } }