Java notes: questions about complex data storage-basics: arrays and questions about shallow and deep copies (II)

Source: Internet
Author: User

Let's first take a look at the followingCode:

 
PackageCn.com. sxia;

Public ClassRefobj {

Public Static VoidMain (string [] ARGs ){
String str1;//@ 1
String str2 =NewString ();//@ 2
System. Out. println (str2.equals (""));
System. Out. println (str1.equals (""));
}

}

The code is defining strings. I want to learn allProgramming LanguagePeople know what is going on, but the two are different:@ 1The reference of the string object is created, but the actual object is not created.,@ 2Both the reference of the string object and the reference object are created (in fact, we often perform initialization operations)As you can see, if we use str2 objectsProgramIt can run normally, but if we use str1, the program will report a compilation error. The error content is as follows:

 
The local variable str1 may not have been initialized

So how is reference defined in Java?

Reference: The identifier that can operate Java objects is called reference..

Let's look at the above example. The reference refers to the two identifiers str1 and str2. Some people will be wondering: What we want is an object. Now, we only see the object identifier, so where did the object go? To answer this question, we need to talk about the relationship between objects and references. Their relationships are:The relationship between objects and references can be imagined as a remote control (reference) and a TV (object). Users can control the use of the TV through the remote control, we need to transfer the right to operate the TV, that is, to control the remote control..

This method of storing and operating objects is not mysterious in programming languages. In fact, the method in Java is relatively simple, it is much simpler than pointers in C or C ++. I also want to emphasize that many people think that references in Java are pointers in C, but many classic Java books deny this statement, I used to interview someone who asked me this question, but at that time I answered the question "pointer". Although many times the interview has not been rejected, some people will answer the question, finally, you don't know how to answer the question,In fact, references in Java can be used as pointers, but these pointers are limited and cannot be controlled by users, if this problem occurs again, I will say that the reference in Java is a castrated pointer..

The storage of variables in programming languages comes down to the memory allocation problem at the bottom of the computer. Knowing how data is allocated in the memory in Java will be helpful for programming, there are six different storage methods in Java:

 Register : This is the fastest storage region, because it is located in a different place from all other storage methods: Inside the processor. However, the number of registers is very limited, so the registers are allocated by the compiler as needed. We have no direct control over this, and it is impossible to find any trace of the Register in our program.
Stack : It resides in the regular RAM (Random Access to memory) region, but can be directly supported by its "Stack pointer. If the stack pointer moves downward, a new memory is created. If it moves upward, the memory is released. This is a fast and efficient data storage method, second only to registers. When creating a program, the Java compiler must accurately know the "length" and "Storage Time" of all data stored in the stack ". This is because it must generate the corresponding code to move the pointer up and down. This restriction undoubtedly affects the flexibility of the program, so although some java data needs to be stored in the stack-especially the object handle, Java objects are not put in it.
Heap : A general-purpose Memory Pool (also in the ram region) that stores Java objects. Unlike the stack, the most attractive thing about "memory Heap" or "Heap" is that the compiler does not have to know how much storage space is allocated from the heap, you do not need to know how long the stored data will stay in the heap. Therefore, it is more flexible to store data in a heap. When creating an object, you only need to use the new command to compile the relevant code. When the code is executed, data is automatically saved in the heap. Of course, to achieve this flexibility, you must pay a certain price: It will take longer to allocate storage space in the heap!
Static storage : Here "static" refers to "in a fixed position" (although also in Ram ). During the running of the program, the static storage data is waiting for calling at any time. Available Static Keyword indicates that a specific element of an object is static. However, Java objects are never placed in static buckets.
Constant Storage : Constant values are usually directly placed inside the program code. This is safe because they will never change. Some constants must be strictly protected, so you may consider placing them in read-only memory (ROM ).
Non-ram Storage : If the data is completely independent from a program, the program still exists when it is not run and is out of the control scope of the program. Two major examples are "stream object" and "fixed object ". For stream objects, the object is converted into a byte stream, which is usually sent to another machine. For fixed objects, objects are stored on disks. Even if the program stops running, they can remain in their own State. A particularly useful technique for these types of data storage is that they can be stored in other media. Once needed, they can even be restored to common, Ram-based objects.

The basic types and references in Java are stored in the stack, because they occupy less space and do not need to be stored in the heap memory, so it is more efficient to use them in the stack. Here we will also talk about arrays. Arrays can be equivalent to objects, even if you are creating an array of the basic type,Arrays can be used as objects..

Now we can go back to what we will talk about in the previous article:In Java, objects are transmitted and returned through reference.This is the crux of the system. arraycopy method. The following code shows that Java is passed by reference: we pass a reference to a method, and we find that the passed reference still points to the original object in the method, let's look at the following code:

PackageCn.com. sxia;

Public ClassPassref {

Public Static VoidF (passref h ){
System. Out. println ("H inside f ():" + H );
}
Public Static VoidMain (string [] ARGs ){
Passref P =NewPassref ();
System. Out. println ("P inside main ():" + p );
F (p );
}

}

The running result is as follows:

 
P inside main (): cn.com. sxia. passref @ 119298d
H inside f (): cn.com. sxia. passref @ 119298d

We can see that both P and h reference point to the same object because their addresses are the same.

There is another alias effect problem in Java.

Alias effect: multiple references point to the same object. This is the case where multiple remote controls on a TV set have suddenly changed one remote control. Other remote controls may not want to be changed. This is a problem.

Let's look at the following code:

PackageCn.com. sxia;

Public ClassAlias {

Private IntI;

PublicAlias (IntIi ){
I = II;
}

Public Static VoidMain (string [] ARGs ){
Alias x =NewAlias (7 );
Alias y = X;
System. Out. println ("X:" + X. I );
System. Out. println ("Y:" + Y. I );
System. Out. println ("add the I value in variable X :");
X. I ++;
System. Out. println ("X:" + X. I );
System. Out. println ("Y:" + Y. I );
}

}

The running result is as follows:

X: 7
Y: 7
Add the I value in variable X:
X: 8
Y: 8

We can see that the values of the X and Y variables have been changed. Most of the time we don't want this situation to happen. The solution to this problem is simple:Do not generate references for multiple objects in the same scope, especially when passing values, we do not use local variables to store incoming values..

But in a local environment (a local environment is the scope of a method), this problem will always occur when we pass parameters from the outside. So in a local environment, that is, in the scope of a method, what is the situation of variables and objects? I'm glad some people have summarized the following situation:

    1. When we pass the parameter alias to the method, the effect will occur.. This is easy to understand. When passing parameters, there is a reference outside the local environment and the reference of parameters inside the local environment all point to the same object, multiple references point to the same object, which is an alias effect.
    2. In a local environment, we construct an object, which has references. The reference belongs to this local environment and is destroyed after being referenced in a local environment, however, the created object will still exist, especially when we use the return keyword to return the object, another external reference will be used for this object,Therefore, there are no local objects in a local environment and only local references are allowed..
    3. The above problem also leads to a situation:In a local environment, the reference has a scope, but the object does not exist. The destruction of the object is recycled by the garbage collection mechanism within a certain period of time after the object can be referenced..
    4. In Java, we care about the reference lifecycle, not the object lifecycle. The object lifecycle is managed by Java itself..

Although there are many problems with the transfer of references, the transfer of references is the default transfer method of Java, because in most cases, the reference will not affect the proper running of our program, in addition, passing parameters only transmits references, that is, only reading the memory of the stack, which is more efficient. Therefore, sometimes we can unilaterally understand that references are a compromise made by Java for program efficiency.

Next I will write a code for the shortest copy. In this small series, I will not conduct in-depth analysis on the issue of writing correct copies, because I want to focus on learning the complex data storage methods in Java, I just come up with a very important point from the shallow copy: What is passed in Java is to reference this truth, this is very helpful for me to write complex data storage issues later. However, in my subsequent content, I will further explain the problems of deep copy and shallow copy, and solve the problems of correct copy will be interspersed with me.Article. Let's take a look at the following code:

 Package Cn.com. sxia;

Import Java. util. arrays;

Class Int {
Private Int I;

Public INT ( Int J ){
I = J;
}

Public Void Increment (){
I ++;
}

Public String tostring (){
Return Integer. tostring (I );
}
}

Public Class Cloning {

Public Static Void Main (string [] ARGs ){
Int [] arr1 = New Int [10];
For ( Int I = 0; I <10; I ++ ){
Arr1 [I] = New INT (I );
}
System. Out. println ("arr1:" + arrays. tostring (arr1 ));
Int [] arr2 = arr1.clone ();
For ( Int J = 0; j <arr2.length; j ++ ){
Arr2 [J]. increment ();
}
System. Out. println ("arr1:" + arrays. tostring (arr1 ));
}

}

The running result is as follows:

 
Arr1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Arr1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

We use the clone method for replication. arr1 is copied to arr2, but the change of arr2 affects the value of arr1. This indicates that this copy is a shortest copy, and arr2 only copies the reference of arr1, the objects pointed to by arr1 are not copied.In fact, objects in Java are composed of the following parts: Object Reference, reference object pointing to, these objects pointing to other objects, this constitutes an object network diagram. Deep COPY Copies the entire object network diagram..

The following content explains how to use multiple java. util packages. This is my focus.

 

 

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.