Java Exchange two digital locations

Source: Internet
Author: User


The first type: in main output, through reflection implementation
1
Public Static voidMain (string[] args)throwsException {2Integer A = 1;3Integer B = 2;4 Swap (A, b);5System.out.println ("a=" + A + "--------b=" +b);6 }7 8 Public Static voidSwap (integer i1, integer i2)throwsException {9 //How to change here, can not be output here, so that the main method of a, a, and a two value exchangeTenInteger temp =NewInteger (I1.intvalue ()); OneField I1value = I1.getclass (). Getdeclaredfield ("value"); AI1value.setaccessible (true); - I1value.set (I1, I2.intvalue ()); -Field I2value = I2.getclass (). Getdeclaredfield ("value"); theI2value.setaccessible (true); - i2value.set (I2, temp); - -}
//Second kind of simple exchange or something like that
1
/** 2 * Exchange Value Demo shows a simple example of space change time, and time-to-change space.3 * 4 * @authorWeep5 * 6 */ 7 Public classswapab {8 Public Static voidMain (string[] args) {9 //two kinds of value exchange, the spatial complexity of the intermediate variable is higher than without the intermediate variable, but the time complexity is less than the intermediate variable. Ten One //General write two-value exchange A intA = 100; - intb = 200; -SYSTEM.OUT.PRINTLN ("Initial value a=100 b=200"); the //Intermediate Variables - intC; - - //Copy to intermediate variable, temporarily save +c =A; - //assign the value of B to a. +A =b; A //assigns the initial value of a stored in C to the normal value exchange . atb =C; -System.out.println ("a =" + A + ", B =" +b); - //Do not use the middle variable notation -A = a +b; -b = A-b; -A = A-b; in -System.out.println ("a =" + A + ", B =" +b); to + //The second one does not need the intermediate variable, the operation, the efficiency is higher than the addition -A = a ^b; theb = a ^b; *A = a ^b; $ Panax NotoginsengSystem.out.println ("a =" + A + ", B =" +b); - the } +}

Java Exchange two digital locations

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.