1

I have a list

var theDataList: List<Data> // populated with some data

and made a copy of it

val copy = theDataList.toMutableList()

downstream in the code it would like to verify whether it is the copy one or the original one

the .hashCode() returns same for both

If just want to use Log to print out, how to do it?

the Log.d("+++", "theDataList: ${theDataList.hashCode()}, copy: ${copy.hashCode()"}) print out same number.

And Log.d("+++", "copy: ${copy}") prints out the list content

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
lannyf
  • 9,865
  • 12
  • 70
  • 152
  • @Innyf pls choose an answer :) – Willi Mentzel Mar 07 '19 at 08:11
  • @Willi Mentzel, thanks for your help, but still dont get the answer for what if I want print out something like the address or internal id for this `theDataList`? the hashCode are same for copy and the orginal, and Log.d("+++", "$theDataList") prints out the content of the list, and Log.d("+++", "${theDataList.hashCode()}") is same as printout out the Log.d("+++", "${copy.hashCode()}") – lannyf Mar 08 '19 at 13:57
  • @Iannyf there is nothing like an address value you could really rely on. See this answer: https://stackoverflow.com/a/1961150/1788806 – Willi Mentzel Mar 10 '19 at 15:52
  • so the answer is "no, it cannt show the identity in the Log or println". – lannyf Mar 11 '19 at 20:02
  • @Iannyf yes, I edited my answer to include that. – Willi Mentzel Mar 16 '19 at 16:12

2 Answers2

3

Problem:

The hash code for both lists is the same because it is based on the data in the list, which is the same.

Solution:

What you actually want is to compare the references of both lists. You can do that with Kotlin's referential equality operator ===.

theDataList === copy // false

There is no ID/hash you can rely on to identify an object on the JVM the way you want. For more info take a look here.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
2

Use the === operator to compare references are the same (not calling equals method)

Eugene Petrenko
  • 4,874
  • 27
  • 36