How to exchange two numbers in Java

Source: Internet
Author: User

In C/C ++, we can use pointers or references to solve the problem, such as the following C code:


Void swap (int * a, int * B)
Int temp = *;
* A = * B;
* B = temp;

Or the following C ++ code:


Void swap (Int & A, Int & B)
Int temp =;
A = B;
B = temp;

However, it is troublesome to implement this function in Java.

You can try it first.


I will describe how to implement this function below:


Class wrappednumber <t extends number> ...{

Private t I = NULL;

Public wrappednumber (t I )...{
This. I = I;

Public t getnumber ()...{
Return I;

Public void setnumber (t I )...{
This. I = I;

Public class hello ...{

Public static <t extends number> void swap (wrappednumber <t> A, wrappednumber <t> B )...{
T temp1 = A. getnumber ();
A. setnumber (B. getnumber ());
B. setnumber (temp1 );

Public static void main (string [] ARGs )...{

Wrappednumber <short> A = new wrappednumber <short> (short) 10 );
Wrappednumber <short> B = new wrappednumber <short> (short) 20 );

Hello. <short> swap (A, B );

System. Out. println ("the answer is: a =" + A. getnumber () + ", B =" + B. getnumber ());
Related Article

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: 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.