Effective Java chapter II objects (2)

Source: Internet
Author: User

Do not create unnecessary objects

I. Some objects are not created after they are changed, and reusable objects are no more than re-created.

Two. Basic types can be used as much as possible using basic type calculations, and packaging types are less efficient than basic types

Like what:

public static void Main (string[] args) {
Long i=0l;

Long i=0l;
for (int j=0;j<1000000;j++) {
I+=1;
}

Loop 1 million times long type time difference 7

The reason is that by using the long type, the JVM automatically splits I into a long object, and then it is boxed into a long object, which is constantly unpacking and boxing, so it is inefficient

About the Equals method and Hashcode method for objects

When it comes to the Equals method, it must be said = =, the difference between the two is simply that equals compares the object's "value" is equal,

= = is divided into two cases, whether the composite object compares the same object, compared to the memory of their storage address. If you use = = for the base type, compare their values.

The Equals method of the object to determine if the object is equals

The Hashcode method must be overridden when overriding the Equals method

Why

For example, there is a cat class that overrides the Equals method. Then use HashMap to store the Map.put (new Cat (name), "112");

Then in map.get (new Cat (name)); The return value is null

Why

HashMap first put the object into the corresponding hashbucket according to the hashcode, HashMap executes the Get method will be based on the key object hashcode from Hashbucket to find,

If you call the Equals method of the object again, the above map map.get (new Cat) object cannot find value because the Cat object does not override the Hashcode method.

Effective Java chapter II objects (2)

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.