Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-04-22 19:55:06
forward
1441 people have browsed it

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()的内存地址
Copy after login

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);         }     }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template