0

I am attempting to implement a Generic Heap. To insert the data I must compare the array for position. When I had this as only integers i was able to use this

   while (heap[getParent(currentItem)] > heap[currentItem]) {

Converting to Generics I researched and attempted this:

while (heap[getParent(currentItem)].compareTo(heap[currentItem]) < 0) {

This was unsuccessful as it gives a NullPointerException. How can I convert the code to properly compare the items?

fox.josh
  • 185
  • 1
  • 8
  • 3
    [How do I fix NullPointerException](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – markspace Nov 22 '15 at 23:27
  • I understand the NullPointerException but I do not understand yet how to convert my initial while loop to one that will compare Generics causing me to get the NullPointerException. The reference you listed relates nothing to the comparing of Generics. – fox.josh Nov 22 '15 at 23:37
  • And generics have nothing to do with the answer. It's just a null pointer exception. You fix it the same as any other: don't store nulls in your array. – markspace Nov 22 '15 at 23:38

1 Answers1

0

You need to use a generic type that extends comparator, such as <T extends Comparable<T>> instead of just <T>. Then you'll be able to compare items using compareTo method. If you are getting a null pointer exception, then you need to make sure that the object that you are trying to call compareTo on should not be null. In your case, that would be heap[getParent(currentItem)]. I would suggest storing heap[getParent(currentItem)] into a field and makins sure that it is not null.

Harsh Poddar
  • 2,394
  • 18
  • 17