File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .base ;
2+
3+ public class Swap {
4+ public static void main (String [] args ) {
5+ int x = 5 ;
6+ int y = 10 ;
7+ swap (x ,y );
8+ System .out .println ("使用swap1()交换:" );
9+ System .out .println (x );
10+ System .out .println (y );
11+
12+ Value v = new Value (5 ,10 );
13+ swap (v );
14+ System .out .println ("使用swap()2交换:" );
15+ System .out .println (v .x );
16+ System .out .println (v .y );
17+ }
18+
19+ // 无效的交换:形参的改变无法反作用于实参
20+ public static void swap (int x ,int y ) {
21+ int temp = x ;
22+ x = y ;
23+ y = temp ;
24+ }
25+
26+ // 有效的交换:通过引用(变量指向一个对象)来修改成员变量
27+ public static void swap (Value value ) {
28+ int temp = value .x ;
29+ value .x = value .y ;
30+ value .y = temp ;
31+ }
32+ }
33+
34+ class Value {
35+ int x ;
36+ int y ;
37+
38+ public Value (int x ,int y ) {
39+ this .x = x ;
40+ this .y = y ;
41+ }
42+ }
43+
You can’t perform that action at this time.
0 commit comments