My set of custom objects accepts duplicates (Kotlin)

530 Views Asked by At

I have a quick question about Sets and custom objects in Kotlin. I have a simple 3D Point class and I would like to have a set of these.

class Point3D(val x: Int, val y: Int, val z: Int){

    override fun equals(other: Any?): Boolean {
        if (other == null) return false
        if (other is Point3D && (this.x != other.x || this.y != other.y || this.z != other.z)) return false
        return true
    }

    override fun toString(): String {
        return "Point(${this.x}, ${this.y}, ${this.z})"
    }
}

When I make a set, I can add several Points with identical coordinates. I tried to override the equality operator but that still doesn't seem to fix it. How can I avoid duplicate objects being added to sets?

1

There are 1 best solutions below

0
distracted_coder On

Thanks guys, both reimplementing hashCode() and declaring data class worked