- 1基本概念
1.1动态初始化
数组动态初始化:数据类型 [] 数组名称 = new 数据类型 [长度]
>>>数组是一个有限的集合,采用 for 循环
>>>动态获取数组长度 :数组名称 . length
>>>数组属于引⽤数据类型,因此在使⽤之前⼀定要开辟空间(实例化),否则就会产⽣ NullPoninterException
1.2数组引用传递
引⽤传递空间:同⼀块堆内存空间可以被不同的栈内存所指向(即多个栈内存指向相同的堆内存)。
2.数组与方法互操作
2.1方法接收数组
public class ArrayDemo{
public static void main(String[] args) {
int[] data = new int[] {1,2,3,4,5} ;
printArray(data) ; // 其效果等价于 int[] temp = data ;
}
public static void printArray(int[] temp) {
for (int i = 0 ; i<temp.length ; i++) {
System.out.println(temp[i]) ;
}
}
}
2.2方法返回数组
public class ArrayDemo{
public static void main(String[] args) {
int[] data = init() ;
printArray(data) ;
}
// 定义⼀个返回数组的⽅法
public static int[] init(){
return new int[] {1,2,3,4,5} ; // 匿名数组
}
public static void printArray(int[] temp) {
for (int i = 0 ; i<temp.length ; i++) {
System.out.println(temp[i]) ;
}
}
}
2.3方法修改数组
public class ArrayDemo{
public static void main(String[] args) {
int[] data = init() ;
bigger(data) ;
printArray(data) ;
}
// 定义⼀个返回数组的⽅法
public static int[] init(){
return new int[] {1,2,3,4,5} ; // 匿名数组
}
// 将数组中每个元素的值扩⼤5倍
public static void bigger(int[] arr){
for (int i =0 ; i<arr.length ; i++) {
arr[i]*=5 ; // 每个元素扩⼤5倍
}
}
public static void printArray(int[] temp) {
for (int i = 0 ; i<temp.length ; i++) {
System.out.println(temp[i]) ;
}
}
}
3.JAVA对数组的支持
3.1实现数组排序
Java类库中数组排序操作 :java.util.Arrays.sort(arrayName) ;
>>>只要是基本数据类型的数组,sort⽅法都可以进⾏排序处理(升序处理)
3.2实现数组拷贝
数组拷贝:
1使用 for()循环可以实现数组的部分拷贝;
2使用 clone 实现数组的部分拷贝;
3System.arraycopy(源数组名称,源数组开始点,⽬标数组名称,⽬标数组开始点,拷⻉⻓度);
int[] dataA = new int[]{1,2,3,4,5,6,7,8,9} ;
int[] dataB = new int[]{11,22,33,44,55,66,77,88,99} ;
System.arraycopy(dataB,4,dataA,1,3) ;
4 java.util.Arrays.copyOf(源数组名称,新数组⻓度);
int[] original = new int[]{1,3,5,7,9};
int[] result = Arrays.copyOf(original,10);
4.对象数组
4.1动态初始化
语法:类名称[] 对象数组名称 = new 类名称[⻓度] ;
Person[] per = new Person[3] ; // 数组动态初始化,每个元素都是其对应
数据类型的默认值
per[0] = new Person("张三",1) ;
per[1] = new Person("李四",2) ;
per[2] = new Person("王五",3) ;
4.2静态初始化
Person[] per = new Person[] {
new Person("张三",1) ,
new Person("李四",2) ,
new Person("王五",3)
} ; // 对象数组静态初始化