c語言中,有指針傳遞,可以通過指針操作內(nèi)存的數(shù)據(jù),如交換變量的值可以這樣
#include<stdio.h>
void swap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
printf("%d,%d\n",*a,*b);//輸出6,5
}
int main()
{
int m=5;
int n=6;
swap(&m,&n);
printf("%d,%d\n",m,n);//輸出6,5
return 0;
}
輸出結(jié)果:
6,5
6,5
但是Java中沒有指針,但是有引用數(shù)據(jù)類型傳遞,那傳遞引用數(shù)據(jù)類型可以實(shí)現(xiàn)交換變量的值嗎?
public class Type {
public static void main(String[] args) {
Integer m=new Integer(5);
Integer n=new Integer(6);
swap(m,n);
System.out.println(m+","+n);//輸出5,6
}
static void swap(Integer a,Integer b){
int temp=0;
temp=a;
a=b;
b=temp;
System.out.println(a+","+b);//輸出6,5
}
}
輸出結(jié)果:
5,6
6,5
結(jié)果是并沒有交換成功,原因是什么呢? 探究一下傳參的過程是怎么樣的?
Java中的數(shù)據(jù)分兩種的數(shù)據(jù)類型:
- 基本數(shù)據(jù)類型
- 引用數(shù)據(jù)類型
程序中m,n為引用數(shù)據(jù)類型,m,n存放在棧中,對象存放的堆中
memory
調(diào)用swap方法的時(shí)候,開辟椨邪穑空間,參數(shù)的值a,b由m,n決定,傳遞參數(shù)相當(dāng)于,給變量a,b賦值,也就是引用數(shù)據(jù)類型a,b指向了堆中相應(yīng)的對象,swap方法中交換a,b,但是m,n的指向并沒有改變,所以變量交換沒有成功.
哪里如何利用這個(gè)功能實(shí)現(xiàn)變量交換呢?
使用Number類
public class Number {
int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
public class Type2 {
public static void main(String[] args) {
Number m = new Number();
Number n = new Number();
m.setI(5);
n.setI(6);
swap(m,n);
System.out.println(m.getI()+","+n.getI());//輸出6,5
}
static void swap(Number a, Number b) {
int temp;
temp = a.getI();
a.setI(b.getI());
b.setI(temp);
System.out.println(a.getI()+ "," + b.getI());//輸出6,5
}
}
輸出結(jié)果:
6,5
6,5
封裝Number類,提供set,get方法,實(shí)現(xiàn)了跟C語言傳遞指針的效果,對內(nèi)存的的數(shù)據(jù)操作.