How to Get the Unique Id of an Object Which Overrides Hashcode()

How to get the unique ID of an object which overrides hashCode()?

System.identityHashCode(yourObject) will give the 'original' hash code of yourObject as an integer. Uniqueness isn't necessarily guaranteed. The Sun JVM implementation will give you a value which is related to the original memory address for this object, but that's an implementation detail and you shouldn't rely on it.

EDIT: Answer modified following Tom's comment below re. memory addresses and moving objects.

how do I get a unique ID per object in Java?

java.lang.System.identityHashCode(obj); will do this for you, if you really need it and understand the repercussions. It gets the identity hashcode, even if the method to provide the hashcode has been overridden.

Should hashCode() return an object's unique ID

As your abstract BaseClass is for data classes (a.k.a. value classes) it should define equals and hashCode as abstract and force the implementing, concrete classes to implement them. e.g.:

abstract class BaseItem {
abstract val id: Int
abstract override fun equals(other: Any?): Boolean
abstract override fun hashCode(): Int
}

data class Person(override val id: Int, val name: String) : BaseItem()

data class Product(
override val id: Int,
val name: String,
val cost: BigDecimal
) : BaseItem()

Implementing these functions in the base class and not overriding them in the concrete sub-classes can lead to violations on the equals & hashCode contracts.

Here is an example of symmetry violation if you do not force sub-classes to implement equals/hashCode:

abstract class BaseItem {
abstract val id: Int
override fun equals(other: Any?) = (other is BaseItem) && id == other.id
override fun hashCode() = id
}

class Person(override val id: Int, val name: String) : BaseItem() {
override fun equals(other: Any?): Boolean {
return (other is Person) && id == other.id && name == other.name
}

override fun hashCode() = 31 * (31 + id.hashCode()) + name.hashCode()
}

class Product(
override val id: Int,
val name: String,
val cost: BigDecimal
) : BaseItem()

fun main(args: Array<String>) {
val baseItem1: BaseItem = Person(1, "Oliver")
val baseItem2: BaseItem = Product(1, "grease", BigDecimal.TEN)
println(baseItem1 == baseItem2) // false
println(baseItem2 == baseItem1) // true
}

If equals/hashCode were implemented according to their contracts then both equality checks would always return the same result (true or false, in this case it should be false as Product should also override these functions and check that other is also a Product and check each relevant property, etc.).

See "Item 8: Obey the general contract when overriding equals" and "Item 9: Always override hashCode when you override equals" in Effective Java, Second Edition by Joshua Bloch for more details on these contracts and the problems around different approaches to hierarchical value classes.

How to overwrite the hashcode method that returns a unique hashcode value with its unique entity ID in my defined Java object?

The easiest solution would be to rely on java.lang.Long's built-in hashCode():

@Override
public int hashCode() {
return Long.valueOf(getId()).hashCode();
}

Edit:

As per the comment below, if the id is stored as a java.lang.Long and not a primitive long, it's even simpler:

@Override
public int hashCode() {
return getId().hashCode();
}

Using hashcode for a unique ID

Hash codes can be thought of as pseudo-random numbers. Statistically, with a positive int hash code the chance of a collision between any two elements reaches 50% when the population size is about 54K (and 77K for any int). See Birthday Problem Probability Table for collision probabilities of various hash code sizes.

Also, your idea to use Math.abs() alone is flawed: It does not always return a positive number! In 2's compliment arithmetic, the absolute value of Integer.MIN_VALUE is itself! Famously, the hash code of "polygenelubricants" is this value.

How can I get the unique id of an Object after overwriting its toString() method?

You can call System.identityHashCode() and pass your object as parameter, then you will get it.

How to get unique ID of HttpsUrlConnection Object

The hashCode method is defined on java.lang.Object (and overridden in subclasses when needed), so you can call it on any object. In your case connection.hashCode() should give you the hash code of connection object.



Related Topics



Leave a reply



Submit