Junior — Middle
How can you check if two objects are equal considering their properties might be in different order?
sobes.tech AI
Answer from AI
To check the equality of two objects where properties may be in different orders (for example, two JSON objects or Maps), you need to compare their contents, not the order of elements.
Approaches:
- If these are collections like
MaporSet, use theequals()methods, which are order-independent. - For JSON objects, you can parse them into data structures (e.g.,
JSONObjectorMap) and compare.
Example in Kotlin for comparing two JSON strings regardless of property order:
import org.json.JSONObject
fun jsonEquals(json1: String, json2: String): Boolean {
val obj1 = JSONObject(json1)
val obj2 = JSONObject(json2)
return obj1.similar(obj2) // compares content regardless of order
}
If the objects are custom classes, you can override equals() to compare fields by value, ignoring order if they are collections.
Thus, the key is to compare the contents, not the order of properties.