数组

数组:
一维数组的声明方式:
例:int a1[]; 或 int[] a1;

Java语言中声明数组时不能指定其长度(数组中元素的个数);
例:int a[5];//非法;

数组对象的创建:
Java中使用关键字new创建数组对象,格式:
数组名 = new 数组元素的类型[数组元素的个数]
例:

int s[];
s = new int[5];

数组初始化:
1.动态初始化
数组定义与为数组元素分配空间和赋值的操作分开进行。
例:

int a[];
a = new int[3];
a[0] = 3;
a[1] = 6;
a[2] = 9;

2.静态初始化
在定义数组的同时就为数组元素分配空间并赋值。
例:

int a[] = {3,6,9};

注:
1.元素为引用数据类型的数据中的每一个元素都需要实例化。
2.每个数组都有一个属性length指明它的长度,例:
a.length 的值为数组a的长度(元素个数)。

二维数组
1.二维数组可以看成以数组为元素的数组。例如:
int a[][] = {{1,2},{3,4,5,6},{7,8,9}};
2.Java中多维数组的声明和初始化应按从高维到低维的顺序进行,例如:

 int a[][] = new int [3][];
 a[0] = new int[2];
 a[1] = new int[4];
 a[2] = new int[3];
 
 int t1[][] = new int[][4];//非法

例1:

public class Test{
 public static void main(String args[]){
  int a[][] = {{1,2},{3,4,5,6},{7,8,9}};
  for(int i=0;i<a.length;i++){
   for(int j=0;j<a[i].length;j++){
    System.out.print("a[" +i+ "][" +j+ "]=" + a[i][j] + "  ");
   }
   System.out.println();
  }
 }
}

输出:

a[0][0]=1  a[0][1]=2  
a[1][0]=3  a[1][1]=4  a[1][2]=5  a[1][3]=6  
a[2][0]=7  a[2][1]=8  a[2][2]=9 

例2:

public class Test{
	public static void main(String args[]){
		String[][] s = new String[3][];
		s[0] = new String[2];
		s[1] = new String[3];
		s[2] = new String[2];
		for(int i=0;i<s.length;i++){
			for(int j=0;j<s[i].length;j++){
				s[i][j] = new String("我的位置是:"+ i +","+ j)
			}
		}
		for(int i=0;i<s.length;i++){
			for(int j=0;j<s[i].length;j++){
				System.out.print(s[i][j]+" ");
			}
			System.out.println();
		}
	}
}

输出:

我的位置是:0,0 我的位置是:0,1 
我的位置是:1,0 我的位置是:1,1 我的位置是:1,2 
我的位置是:2,0 我的位置是:2,1 

数组的拷贝
1.使用java.lang.System类的静态方法
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
2.可以用于数组src从第srcPos项元素开始的length个元素拷贝到目标数组从destPos项开始的length个位置。
3.如果源数据数目超过目标数组边界会抛出 IcdexOutOfBoundsException 异常。

例:

public class TestArrayCopy{
	public static void main(String[] args){
		String[] s = {"Mircosoft","IBM","Sun","Oracle","Apple"};//五大公司
		String[] sBak = new String[6];
		System.arraycopy(s,0,sBak,0,s.length);
		for(int i=0;i<sBak.length;i++){
			System.out.print(sBak[i]+" ");
		}
		System.out.println();
		int[][] intArray = {{1,2},{1,2,3},{3,4}};
		int[][] intArrayBak = new int[3][];
		System.arraycopy(intArray,0,intArrayBak,0,intArray.length);
		intArrayBak[2][1] = 100;
		for(int i=0;i<intArray.length;i++){
			for(int j=0;j<intArray[i].length;j++){
				System.out.print(intArray[i][j] + " ");
			}
			System.out.println();
		}
	}
}

输出:

Mircosoft IBM Sun Oracle Apple null 
1 2 
1 2 3 
3 100 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值