Java-based Object class, java-based object

Source: Internet
Author: User

Java-based Object class, java-based object

Class Object is the root class of the class hierarchy. Each class inherits the Object class directly or indirectly. All objects (including arrays) implement this class method. There is only one constructor in the Object class and it is a non-parametric constructor. This means that the default non-parametric constructor in each class calls the non-parametric constructor of the Object class.

1. hashCode Method

The hashCode method returns the hash code of this object to the caller. (The value is calculated by a hash function. Generally, the internal address of this object is converted into an integer ). This method is usually used in hash-based collection classes (such as java. util. HashMap, java. until. HashSet and java. util. Hashtable) to improve performance.

1 @Test2 public void testHashCode() {3     Student student = new Student();4 5     for (int i = 0; i < 3; i++) {6         System.out.println(student.hashCode());7     }8 }
1 2491235372 2491235373 249123537

We can see that the result is the same after running three times. The hashCode method in Java has the following conventions:

1) During Java application execution, the same integer must be returned when the hashCode method is called for the same object multiple times, the premise is that the information used for equals comparison is not modified. This integer does not need to be consistent from one execution of an application to another execution of the same application.
2) If the two objects are equal according to the equals (Object) method, the hashCode method must generate the same integer result for each Object in the two objects.
3) if the two objects are not equal according to the equals (java. lang. Object) method, it is not required to generate different integer results to call the hashCode Method on any of the two objects. However, programmers should realize that generating different integer results for unequal objects can improve the performance of the hash table.

The above three sentences can be understood:

The two objects are equal. <=> equals => hashCode equals.

HasCode not equal => equals not equal <=> two objects are not equal.

I still don't know what this hasCode method is used for. As mentioned above, this method is usually used in hash-based collection classes to improve performance. Take the Set as an example, when adding a new object to the collection, you need to know whether the object exists in the current collection, java will first call the hasCode method to determine whether the hash code value of an object in the set is equal to that of the new object. If not, it will be added. If it is equal, the equals method is used to determine whether two objects are equal. Only when the hash code is equal and the equals method returns true will the two objects be considered equal.

2. equals Method

This method can be used to check whether an object is equal to the object that calls this equals.

Equals literally means equal. When it comes to equality, we think that the = operator is also used to compare equality. What are the differences between the two operators, when = is used for the basic type, it compares whether the values of the basic type are the same. When used for the reference type, it compares whether the address of the reference type points to the same place, the equals and = operators in the Object are the same.

1 public boolean equals(Object obj) {2     return (this == obj);3 }

Now that we have the = Operator, what else do we need the equals method to do? Generally, it is of little significance to compare the address values of two objects, therefore, you need to override the equals method in the Object class to meet your needs. For example, The equals method in the String class indicates whether the content of the String is equal. If you override the equals method, it is also necessary to override the hashCode.

3. getClass Method

Returns the runtime class (Class Object) of this Object. We know that the class is an abstraction and description of instances with the same features or behaviors, an object is a specific instance of the features or actions described by this class. As a class, it also has some common features, such as class names, loaded by the class loader, packages, parent classes, attributes, and methods. In Java, the Class is used to represent these features of other classes. Therefore, classes are also Class objects. To distinguish it from what is usually called an object, it is usually called a class object.

1 @Test2 public void testGetClass() {3     Student student = new Student();4     System.out.println(student.getClass());5 }
class com.java.test.Student

4. toString Method

Returns the string representation of the object. Generally, the toString method returns a string that "represents the object in text. Let's look at the toString method in the Object class.

1 public String toString() {2     return getClass().getName() + "@" + Integer.toHexString(hashCode());3 }

When we use System. out. println (object), it is also implemented by calling toString () internally.

1 @Test2 public void testToString() {3     Student student = new Student();4     System.out.println(student);5     System.out.println(student.toString());6     System.out.println(student.getClass().getName() + "@" + Integer.toHexString(student.hashCode()));7 }
1 com.java.test.Student@cb5efc82 com.java.test.Student@cb5efc83 com.java.test.Student@cb5efc8

Since this information is generally not very useful, we recommend that you override this method for all subclasses. After rewriting the toString method in the Student class

1 Student [name=null, age=0]2 Student [name=null, age=0]

At this time, we can easily understand the information.

5. clone Method

Create and return a copy of this object. A copy can be understood in this way. There was a document that was copied through Ctrl + C, and then Ctrl + V pasted a new document. This new document is called a copy of the document, the operations you perform on the copy will not affect the original document. Note:When calling the clone () method, the called object must implement the Cloneable interface.If the Cloneable interface is not implemented and the subclass directly calls the clone () method of the Object class, a CloneNotSupportedException exception is thrown. The Cloneable interface is a tag interface. The interface itself does not contain any methods, indicating that the interface can be implemented to replicate objects.

1 @ Test 2 public void testClone () throws CloneNotSupportedException {3 Student student1 = new Student ("John", 23); 4 Student student2 = (Student) student1.clone (); 5 System. out. println (student1); 6 System. out. println (student2); 7 System. out. println ("after changing the attribute value of student1:"); 8 student1.setName ("Jack"); 9 student1.setAge (22); 10 System. out. println (student1); 11 System. out. println (student2); 12}
1 Student [name = John, age = 23] 2 Student [name = John, age = 23] 3 after changing the attribute value of student1: 4 Student [name = Jack, age = 22] 5 Student [name = John, age = 23]

The running results also show that the changed attribute value of the called object student1 does not affect the attribute value of the copy, but also shows that the two are in different positions in the heap space.

6. finalize method

1 protected void finalize() throws Throwable { }

When the Garbage Collector determines that there is no more reference to this object, the object's garbage collector calls this method. Generally, this method is not used.

Complete code:

1 package com. java. test; 2 3 import org. junit. test; 4 5 public class StudentTest {6 7 @ Test 8 public void testHashCode () {9 Student student = new Student (); 10 11 for (int I = 0; I <3; I ++) {12 System. out. println (student. hashCode (); 13} 14} 15 16 @ Test17 public void testGetClass () {18 Student student = new Student (); 19 System. out. println (student. getClass (); 20} 21 22 @ Test23 public void testToString () {24 Student student = new Student (); 25 System. out. println (student); 26 System. out. println (student. toString (); 27 System. out. println (student. getClass (). getName () + "@" + Integer. toHexString (student. hashCode (); 28} 29 30 @ Test31 public void testClone () throws CloneNotSupportedException {32 Student student1 = new Student ("John", 23 ); 33 Student student2 = (Student) student1.clone (); 34 System. out. println (student1); 35 System. out. println (student2); 36 System. out. println ("after changing the attribute value of student1:"); 37 student1.setName ("Jack"); 38 student1.setAge (22); 39 System. out. println (student1); 40 System. out. println (student2); 41} 42}
 1 package com.java.test; 2  3 public class Student implements Cloneable { 4     private String name; 5     private int age; 6  7     public Student() { 8         super(); 9     }10 11     public Student(String name, int age) {12         super();13         this.name = name;14         this.age = age;15     }16 17     public String getName() {18         return name;19     }20 21     public void setName(String name) {22         this.name = name;23     }24 25     public int getAge() {26         return age;27     }28 29     public void setAge(int age) {30         this.age = age;31     }32 33     @Override34     public String toString() {35         return "Student [name=" + name + ", age=" + age + "]";36     }37 38     @Override39     protected Object clone() throws CloneNotSupportedException {40         return super.clone();41     }42 43 }

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.