Common Object methods of the Kotlin series, common objects of kotlin
Today we will talk about the Common Object methods in Kotlin.
What is a common object method? It is actually a method owned by all objects. Further, it isToString (),Equals () andHashCode (). Let's take a look at these methods in Kotlin today.
Old Rules: Let's take a look at some knowledge points of the three methods in Java, and then compare them.
Common Object methods in Java
In Java, these methods are all Object methods.
ToString () is used to represent the string of an object. Most of the time it appears, it is used to print the object attributes in the string format. If we do not rewrite an object'sToString () method, the default value isClass Name @ 53ffe12a. We can rewrite this method of the object to make the printed results more intuitive and better understood.
The equals () method is used to determine whether two objects are equal. By default, its function and= Is used to compare the references (addresses) of two objects. We can rewrite this method to compare the attributes of two objects.
The hashCode () method is used to calculate the hash value of an object.
Note that there is such a contract in Java: If two objects useEquals () methods are equal, so theirThe hashCode () value must be equal, but ifThe hashCode () value is equal, and the two objects are not equal at all.
The following code is used for a brief look:
Java code
Public class User {private String name; private int age; public User (String name, int age) {this. name = name; this. age = age ;}@ Override public boolean equals (Object o) {if (this = o) return true; if (o = null | getClass ()! = O. getClass () return false; User user = (User) o; if (age! = User. age) return false; return name! = Null? Name. equals (user. name): user. name = null;} @ Override public int hashCode () {int result = name! = Null? Name. hashCode (): 0; result = 31 * result + age; return result ;}@ Override public String toString () {return "User {" + "name = '" + name +' \ ''+", age = "+ age + '}';} public static void main (String [] args) {User user2 = new User ("Rain", 21); User user1 = new User ("clear", 21); System. out. println (user1); System. out. println (user1.equals (user2); System. out. println (user1.hashCode (); System. out. println (user2.hashCode ());}}
Running result
User {name = 'Qing', age = 21} false8130891197613
The above code overwrites these methods, just for a simple review, then let's take a look at the above Code using Kotlin to write it?
Common Object methods in Kotlin
The same is true in Kotlin. We also need to rewrite it.ToString () method. As shown below.
Kotlin code
Open class User (val name: String, val age: Int) {override fun toString () = "User {name = '$ name ', age = $ age} "} fun main (atgs: Array ) {Val user1 = User ("", 21); println (user1 )}
The above code is rewritten.The result of the toString () method is the same as that of java. Note thatThe override keyword is mandatory. At the same time, we also used$ Variables are directly referenced in strings in the form of variable names. Kotlin will automatically replace them with the corresponding variable values, which is a template string in Kotlin.
Next let's take a look.Equals () method andOverride of the hashCode () method. Same contract as in Java,Equals () method andThe hashCode () method must be synchronized and overwritten.
Kotlin code
open class User(val name: String, private val age: Int){ override fun toString() = "User{name='$name', age=$age}" override fun equals(other: Any?): Boolean { if (other == this){ return true; } if (other == null || other !is User){ return false; } return name == other.name && age == other.age } override fun hashCode(): Int { var result = name.hashCode() ?: 0 result = 31 * result + age return result }}
The above code is rewritten.Equals () andHashCode () method.
Some people may have questions. Here, I would like to add,Any is equivalent to an Object in Java, but the following method does not forcibly convert the type of other to the User when getting the name attribute. This is one of the major features of Kotlin.Intelligent conversion.
Note that in Kotlin= Is used to compare two basic types of values and two objects, equivalentEquals (), which callsEquals () method. To compare the attributes of two objects, you can use=.
Here, I will explain why we need to maintainEquals () andHashCode () consistency. We all know that the data structure Set is to ensure that all the elements are unique, and there is only one. In the HashSet collection, optimization is performed to compare the hash values of the two objects first, if the hash value is equal, then compare the values of the two objects. If the hash value is not equal, it is considered to be two identical elements. If we cannot guarantee the object'sEquals () andIf hashCode () is consistent, an error occurs when this set is used.
Conclusion
Pay attention to the above comparison.= It is different in Java and Kotlin. It also finds the same function. Kotlink can be implemented with more concise code. In the following section, we will learn more concise code.