java按值传递(2)两整数交换

xiaoxiao2021-02-27  237

java下面的函数是不能成功交换两个整数的

public void swap1(int a,int b){ //java值参数传递不能实现交换两个整数 int t; t = a; a = b; b = t; }

在C++,可以通过引用或者指针来实现两个整数的交换,实质上是通过地址传递来实现两个整数的交换的。

void swap2(int &a,int &b)//引用传递 { int temp; temp = a; a = b; b = temp; }

还可以通过指针来实现两个整数的交换

void swap2(int *a,int *b)//指针,地址传递 { int temp; temp = *a; *a = *b; * b = temp; }

那么,java如何实现两书交换呢?

方法1: 通过数组方式交换:

如果一定要通过一个 method 来实现,下面的形式也许可以:

void swap(int[] a) { if (a == null || a.length != 2) throw new IllegalArgumentException(); int temp = a[0]; a[0] = a[1]; a[1] = temp; }

2)方法2:构造引用

如AtomicReference 构造对象,将a,b作为对象的属性,然后操作对象,最后获得对应的属性。

static void swap(AtomicReference<Integer> a, AtomicReference<Integer> b) { Integer c = a.get(); a.set(b.get()); b.set(c); } public static void main(String[] args) { AtomicReference<Integer> a = new AtomicReference<Integer>(10); AtomicReference<Integer> b = new AtomicReference<Integer>(20); swap(a, b); System.out.println("a = " + a); System.out.println("b = " + b); } //a = 20 b = 10
转载请注明原文地址: https://www.6miu.com/read-10949.html

最新回复(0)