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);
}
}
}
本文详细介绍了Java中数组的操作,包括值传递的特点、增强for循环的使用、数组的排序及合并方法,并通过具体实例展示了不同操作的效果。
574

被折叠的 条评论
为什么被折叠?



