Home  >  Article  >  Java  >  How to use clone() method in Java instead of new keyword?

How to use clone() method in Java instead of new keyword?

WBOY
WBOYforward
2023-04-22 19:55:061400browse

Use clone() instead of new

The most common way to create a new object instance in Java is to use the new keyword. JDK's support for new is very good. When using the new keyword to create lightweight objects, it is very fast. However, for heavyweight objects, the execution time of the constructor may be longer because the object may perform some complex and time-consuming operations in the constructor. As a result, the system cannot obtain a large number of instances in the short term. To solve this problem, you can use the Object.clone() method.

The Object.clone() method can bypass the constructor and quickly copy an object instance. However, by default, the instance generated by the clone() method is only a shallow copy of the original object.

I have to mention here that Java only transfers by value. Regarding this point, my understanding is that basic data types refer to values, and ordinary objects also refer to values. However, the value referenced by this ordinary object is actually an object. the address of. Code example:

int i = 0; int j = i; //i的值是0  User user1 = new User();  User user2 = user1; //user1值是new User()的内存地址

If you need a deep copy, you need to reimplement the clone() method. Let's take a look at the clone() method implemented by ArrayList:

public Object clone() {                try {             ArrayList<?> v = (ArrayList<?>) super.clone();             v.elementData = Arrays.copyOf(elementData, size);             v.modCount = 0;                         return v;         } catch (CloneNotSupportedException e) {                         // this shouldn't happen, since we are Cloneable             throw new InternalError(e);         }     }

In the clone() method of ArrayList, first use the super.clone() method to generate a shallow copy object. Then copy a new elementData array for the new ArrayList to reference. The cloned ArrayList object has different references from the original object, thus realizing a deep copy.

The above is the detailed content of How to use clone() method in Java instead of new keyword?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete