类的参数传递,增强For遍历数组,返回值


1,
public class Person {
	String name="";
	public void test(int a){
		a=30;
	}
	public int test1(int a){
		a=30;
		return a;
	}
	public void test2(int[] a){
		a[0]=30;
	}
	public static void main(String[] args) {
		Person p=new Person();
		p.name="yy";
		Person p1=p;
		p1.name="zx";
		System.out.println(p.name);		//zx
		
		
		int x=40;
		p.test(x);
		System.out.println(x);  	//x=40
		x=p.test1(x);		
		System.out.println(x);		//x=30
		
		
		
		int[] y={1,2,3};
		p.test2(y);
		System.out.println(y[0]);    //30
		
	}

}
  • 1.类也是一种数据类型——复合/引用类型
  •  即只改变栈,不改变堆
  • 2.p.test(x)相当于值的传递过程int  a=x;
  • 第二种情况有返回值,返回a送回x,所以x=40

2.增强For遍历一维数组与二维数组

public class zqFor {
	public void test(int[] a){
		for(int x:a){
			System.out.println(x);
		}
	} 
	public void test2(int[][] s){
		for(int[] s1:s){
			for(int s2:s1){
				System.out.println(s2);
			}
		}
	}

	public static void main(String[] args) {
		zqFor zq=new zqFor();
		int[] b={4,3,8,1,6};
		zq.test(b);
		int[][] t={{1,2},{3,5}};
		zq.test2(t);

	}

}


3.排序数组

public class szPX {
	public int[] test(int[] a){
		for(int j=0;j<a.length-1;j++){
		for(int i=a.length-1;i>j;i--){
			if(a[i]<a[i-1]){
				int sum=a[i]+a[i-1];
				a[i]=sum-a[i];
				a[i-1]=sum-a[i];
			}
		}
		}
		return a;
	}
	public static void main(String[] args) {
		szPX sz=new szPX();
		int[] b={4,2,5,2,1};
		int[] w=sz.test(b);
		for(int x:w){
			System.out.println(x);
		}
		
	}

}


 

引用类型可以不用返回值(利用栈的改变)

public class szPX2 {
	public void test(int[] a){
		for(int j=0;j<a.length-1;j++){
		for(int i=a.length-1;i>j;i--){
			if(a[i]<a[i-1]){
				int sum=a[i]+a[i-1];
				a[i]=sum-a[i];
				a[i-1]=sum-a[i];
			}
		}
		}
	}
	public static void main(String[] args) {
		szPX sz=new szPX();
		int[] b={4,2,5,2,1};
		sz.test(b);
		for(int x:b){
			System.out.println(x);
		}
		
	}

}


 

但也不使用于所有情况:方法内产生新的数组需要带返回值

4.数组合并

public class szHebing {
	
	public int[] Hebing(int[] a,int[] b){
		int[] c=new int [a.length+b.length];
		int[] w=a;
		for(int i=0;i<c.length;i++){
			if(i==a.length){
				w=b;
			}
			c[i]=w[i%a.length];
		}
		return c;
	}
	public static void main(String[] args) {
			int[] x={2,4,7,3};
			int[] y={4,3,2};
			szHebing sz=new szHebing();
			int[] s=sz.Hebing(x,y);
			for(int k:s){
				System.out.println(k);
			}
			
	

	}

}


 


public class szPX {
	public int[] test(int[] a){
		for(int j=0;j<a.length-1;j++){
		for(int i=a.length-1;i>j;i--){
			if(a[i]<a[i-1]){
				int sum=a[i]+a[i-1];
				a[i]=sum-a[i];
				a[i-1]=sum-a[i];
			}
		}
		}
		return a;
	}
	public static void main(String[] args) {
		szPX sz=new szPX();
		int[] b={4,2,5,2,1};
		int[] w=sz.test(b);
		for(int x:w){
			System.out.println(x);
		}
		
	}

}


 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值