JAVA用一个函数交换两个数字

JAVA用一个函数交换两个数字

1.方法

直接交换和用包装了交换都不能交换两个数的值!!!
而采用数组交换和成员变量交换是可以做到的

package com.wq.swap;

public class SwapNumbers {
public int a;
public int b;

//包装类交换
public static void swap (Integer a, Integer b) {	
	Integer temp = a;
	a = b;
	b = temp;
};

//直接交换
public static void swap (int a, int b) {	
	int temp = a;
	a = b;
	b = temp;
};

//数组
public static void swap (int[] arr) {	
	int temp = arr[0];
	arr[0] = arr[1];
	arr[1] = temp;
};

//成员对象
public  void swapNum(int a, int b) {	
	this.a = b;
	this.b = a;
};

//包装类打印
public static void print(Integer m, Integer n) {
	System.out.println("m=" + m.intValue() + " n=" + n.intValue());
}
//直接打印
public static void print(int a, int b) {
	System.out.println("a=" + a + " b=" + b);
}
//对象打印
public  void print() {
	System.out.println("a=" + this.a + " b=" + this.b);
}
//数组打印
public static void print(int[] a) {
	for (int i : a) {
		System.out.print(i + " ");
	}
	System.out.println();
}


public static void main(String[] args) {
	
	System.out.println("------直接交换----------");
	int a = 2, b = 3;
	
	print(a,b);
	swap(a, b);
	print(a,b);
	
	System.out.println("------包装类交换----------");
	Integer m = new Integer(2);
	Integer n = new Integer(3);
	
	print(m,n);
	swap(m, n);
	print(m,n);
	
	System.out.println("-------数组交换---------");
	int[] arr = {2,3};
	print(arr);
	swap(arr);
	print(arr);
	
	System.out.println("-------成员变量交换---------");
	print(a,b);
	SwapNumbers sn = new SwapNumbers();
	sn.swapNum(a, b);
	sn.print();
	
}

}

2.结果:

直接交换----------
a=2 b=3
a=2 b=3
------包装类交换----------
m=2 n=3
m=2 n=3
-------数组交换---------
2 3
3 2
-------成员变量交换---------
a=2 b=3
a=3 b=2
转自 https://blog.csdn.net/feeltouch/article/details/79052460

3.原因分析:

可参考值传递和引用传递
Integer不行,
1、Integer本身是值对象(value object),不能修改它的内容(找找哪个方法能修改它的内容?)。实际上,串对象String都不能改变;
2、就算Integer本身可以修改,自动装箱、拆箱也不灵:

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值