@@ -33,7 +33,7 @@ public class MaxHeap implements Heap {
33
33
34
34
/**
35
35
* Constructs a new MaxHeap from a list of elements.
36
- * Null elements in the input list are ignored with a warning message .
36
+ * Null elements in the input list are ignored.
37
37
*
38
38
* @param listElements List of HeapElement objects to initialize the heap
39
39
* @throws IllegalArgumentException if the input list is null
@@ -45,22 +45,20 @@ public MaxHeap(List<HeapElement> listElements) {
45
45
46
46
maxHeap = new ArrayList <>();
47
47
48
- // Safe initialization: directly add elements first
48
+ // Safe initialization: directly add non-null elements first
49
49
for (HeapElement heapElement : listElements ) {
50
50
if (heapElement != null ) {
51
51
maxHeap .add (heapElement );
52
- } else {
53
- System .out .println ("Null element. Not added to heap" );
54
52
}
55
53
}
56
54
57
- // Then heapify the array bottom-up
55
+ // Heapify the array bottom-up
58
56
for (int i = maxHeap .size () / 2 ; i >= 0 ; i --) {
59
57
heapifyDown (i + 1 ); // +1 because heapifyDown expects 1-based index
60
58
}
61
59
62
60
if (maxHeap .isEmpty ()) {
63
- System . out . println ("No element has been added, empty heap." );
61
+ throw new IllegalStateException ("No valid elements have been added; heap is empty ." );
64
62
}
65
63
}
66
64
@@ -180,7 +178,7 @@ private void toggleDown(int elementIndex) {
180
178
*/
181
179
private HeapElement extractMax () throws EmptyHeapException {
182
180
if (maxHeap .isEmpty ()) {
183
- throw new EmptyHeapException ("Cannot extract from empty heap" );
181
+ throw new EmptyHeapException ("Cannot extract from an empty heap" );
184
182
}
185
183
HeapElement result = maxHeap .getFirst ();
186
184
deleteElement (1 );
@@ -205,7 +203,7 @@ public void insertElement(HeapElement element) {
205
203
@ Override
206
204
public void deleteElement (int elementIndex ) throws EmptyHeapException {
207
205
if (maxHeap .isEmpty ()) {
208
- throw new EmptyHeapException ("Cannot delete from empty heap" );
206
+ throw new EmptyHeapException ("Cannot delete from an empty heap" );
209
207
}
210
208
if ((elementIndex > maxHeap .size ()) || (elementIndex <= 0 )) {
211
209
throw new IndexOutOfBoundsException ("Index " + elementIndex + " is out of heap range [1, " + maxHeap .size () + "]" );
0 commit comments