java realizes value exchange (swap)

 Don't pass by value. Because the formal parameter copies the value of the actual parameter, after the function is called, the space is released, and the exchange result cannot be transmitted. The parameter should be a reference type.

1. The swap function is defined as a public type

public class Test_Swap {
    
    
    //public函数
	public  void swap(int[] brr,int index1,int index2){
    
    
		int tmp=brr[index1];
		brr[index1]=brr[index2];
		brr[index2]=tmp;
		
	}
	public static void main(String[] args) {
    
    
		int[] arr= {
    
    10,20};
		
		//依赖于对象,需要通过 对象.  来调用
		Test_Swap  test=new Test_Swap() ;
		test.swap(arr,0,1);
		
		System.out.println(arr[0]+" "+arr[1]);
	}
}

2. The swap function is defined as a public static type

public class Test_Swap {
    
    
   //定义为静态方法
	public  static  void swap(int[] brr,int index1,int index2){
    
    
		int tmp=brr[index1];
		brr[index1]=brr[index2];
		brr[index2]=tmp;
		
	}
	public static void main(String[] args) {
    
    
		int[] arr= {
    
    10,20};
	
		//两种调用方法
		Test_Swap.swap(arr,0,1);
		//swap(arr,0,1);
		
		System.out.println(arr[0]+" "+arr[1]);
	}
}

Guess you like

Origin blog.csdn.net/qq_41571459/article/details/113532712