Home > Software design >  How should I override "compareTo" so I do not get exception in my code?
How should I override "compareTo" so I do not get exception in my code?

Time:02-02

this is my code:

import java.util.*

open class Food(private var calories: Long) : Comparable<Food> {
//    override fun compareTo(other: Food): Int {
//        return if(this.calories==other.calories)
//            0
//        else if(this.calories>other.calories)
//             1
//        else -1
//    }
    override fun toString(): String {
        return "calories=$calories"
    }
//    override fun compareTo(other: Food)=compareValuesBy(this, other,
//            { it.calories },
//            { it.calories }
//        )
}


class Flafel():Food(100){
    override fun toString(): String {
        return "Flafel ${super.toString()}"
    }
}
class Pizza():Food(200){
    override fun toString(): String {
        return "Pizza ${super.toString()}"
    }
}
class Hamburger():Food(300){
    override fun toString(): String {
        return "Hamburger ${super.toString()}"
    }
}

class Restaurant {
    val foodList = Array<Food?>(10) {null}
    init {

        for (i in 0 until foodList.size-1) {
            var newObject=when((1..3).random()){
                1->Flafel()
                2->Pizza()
                else->Hamburger()
            }
            foodList[i]=newObject
        }
        Arrays.sort(foodList)
        for (i in 0 until foodList.size-1) {
            println(foodList[i])
        }
    }
}
fun main() {
    var lobsterRestaurant=Restaurant()
}

I have tried two kind of code (which is commented in the code) but I get this exception:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because "pivot" is null at java.base/java.util.ComparableTimSort.binarySort(ComparableTimSort.java:262) at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:189) at java.base/java.util.Arrays.sort(Arrays.java:1041) at Restaurant.(Main.kt:50) at MainKt.main(Main.kt:57) at MainKt.main(Main.kt)

CodePudding user response:

Problem is in this part of code:

for (i in 0 until foodList.size-1)

You leave the last 10th element of array unfilled an it stays null, so it causes an NPE. If you would do it like that then it would work:

for (i in 0 until foodList.size)

Thats because until does not include the last number in the range.

  •  Tags:  
  • Related