Get the App
SLTechnology News&Howtos  ›  Development  › 

How java uses clone () instead of new

Shulou Source: shulou.com Published: 2022-06-01 06:01:55 10月27日 Update

This article mainly shows you "java how to use clone () instead of new", the content is easy to understand, clear, hope to help you solve doubts, the following let the editor lead you to study and learn "java how to use clone () instead of new" this article.

Use clone () instead of new

The most common way to create a new object instance in Java is to use the new keyword. JDK supports new very well, and it's very fast to create lightweight objects using the new keyword. However, for heavyweight objects, because the object may perform some complex and time-consuming operations in the constructor, the constructor may take a long time to execute. As a result, a large number of instances can not be obtained in a short period of time. To solve this problem, you can use the Object.clone () method.

The Object.clone () method can quickly copy an object instance, bypassing the constructor. By default, however, the instance generated by the clone () method is just a shallow copy of the original object.

I have to mention that Java only passes values. My understanding is that the basic data type refers to the value, and the ordinary object refers to the value, but the value referenced by this ordinary object is actually the address of an object. Code example:

Int I = 0; int j = I; / / I is 0 User user1 = new User (); User user2 = user1; / / user1 is the memory address of new User ()

If a deep copy is required, the clone () method needs to be reimplemented. 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, you first generate a shallow copy object using the super.clone () method. Then copy a new elementData array for the new ArrayList to reference. The cloned ArrayList object has different references from the original object, and the deep copy is realized.

The above is all the content of the article "how java uses clone () instead of new". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Object method copy instance content function article ordinary keyword address learning help generation different complex code memory just only Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Apple OPPO Reno MySQL MariaDB