I came across with kotlin equals function to compare two list of same type. It works fine for pure Kotlin with data classes.
I'am using a Java library in Kotlin project in which a callback method returns a list of objects for a time interval of X seconds. Trying to compare the old list with new list for every call, but equals returns false even the items are same and equal.
val mOldList: MutableList<MyObject>()? = null
override fun updatedList(list: MutableList<MyObject>){
// other code
if (mOldList.equals(list)) // false everytime
}
Is this because of Java's equals method from library?
Alternative suggestions for list compare would be appreciative.
Java provides a method for comparing two Array List. The ArrayList. equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal.
a==b will evaluate to True only when the value of both "a" and "b" are equal. a===b will evaluate to True only when both "a" and "b" are pointing to the same object.
List<Integer> common = new ArrayList<Integer>(listA); common. retainAll(listB); // common now contains only the elements which are contained in listA and listB. So you can check for size if it is greater than 0 it meanse some elements are common. And which are common elements common will tell.
Just fyi you can call list1 == list2
without any extra work, if your custom object is based off of a data class
(which automatically overrides equals for you).
If you don't bother about order of elements in both lists, and your goal is to just check that two lists are of exactly same elements, without any others, you can consider two mutual containsAll
calls like:
var list1 = mutableListOf<String>()
var list2 = mutableListOf<String>()
if(list1.containsAll(list2) && list2.containsAll(list1)) {
//both lists are of the same elements
}
Java lists implement equals
method and two lists are defined to be equal if they contain the same elements in the same order. I guess, you are missing equals
method in your MyObject
class.
Using zip
zip
returns a list of pairs built from the elements of this array and the other array with the same index. The returned list has length of the shortest collection.
fun listsEqual(list1: List<Any>, list2: List<Any>): Boolean {
if (list1.size != list2.size)
return false
val pairList = list1.zip(list2)
return pairList.all { (elt1, elt2) ->
elt1 == elt2
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With