We can see the pointer and reference, and the implementation of the classic swap () method. Almost everyone knows that to implement a correct swap () method, the pointer or reference must be used as the parameter. For example:
C code
- // Use Pointer
- VoidSwap (Int*,Int* B ){
- IntTMP = *;
- * A = * B;
- * B = TMP;
- }
- // Reference
- VoidSwap (Int&,Int& B ){
- IntTMP =;
- A = B;
- B = TMP;
- }
Suddenly, how does one implement this process in Java? Java does not have the so-called pointer and reference concepts, and all the passing in Java is value passing. That is to say, the following method is not effective in Java:
Java code
- VoidSwap (IntA,IntB ){
- IntTMP =;
- A = B;
- B = TMP;
- }
So this is quite embarrassing. To achieve a correct exchange process, it seems that more complicated things must be done.
If A and B are two member variables in the class, you can directly write the following method:
Java code
- IntA = 4;
- IntB = 5;
- Public VoidSwap (){
- IntTMP =;
- A = B;
- B = TMP;
- }
Because all methods and variables in Java must be declared in a class, A, B, and swap () are in the same class at this time. Therefore, no parameters need to be passed () method directly references the member variables of the object.
Another method is to re-assign values. For example, you can write a variable method:
Java code
- Public Static Int[] Swap (IntA1,IntA2 ){
- IntTMP = A1;
- A1 = a2;
- A2 = TMP;
- Return New Int[] {A1, a2 };
- }
According to the order in which the data is transmitted, the corresponding value is retrieved again. For example:
Java code
- IntA = 4;
- IntB = 5;
- Int[] Swap = swap (A, B );
- A = swap [0];
- B = swap [1];
- System. Out. println (a + "" + B );
It seems that there is no pointer or reference, and there is also a big problem. As a matter of principle, the following method should apply to all exchanges:
Java code
- Public Static<T>VoidSwap (T T1, t T2 ){
- T TMP = T1;
- T1 = t2;
- T2 = TMP;
- }
However, after testing, we will find that this method is always invalid. Therefore, we must always think of other methods to achieve this.