10、分配内存空间
分配内存空间
数组名=new 数据类型[数组长度];
new关键字用来实现为数组或对象分配内存
数组具有固定的长度。获取数组的长度: 数组名.length
定义数组+分配内存空间
数据类型[]数组名=new 数据类型[数组长度];
定义数组时不指定长度,分配空间时指定数组长度;如:String cities[] = new String[6];
数组元素:
数组名[下标值];
数组下标从0开始 scores[0]=75;
数组的内存分配 栈内存和堆内存
如定义一个数组 int[]scores将在栈内存中为scores 分配内存空间,其值是一个不确定的值。
当执行语句scores=new int[5]时,将在堆内存分配连续5个空间,每个空间4个字节,用于存放整型数据,其初始值为0,然后将该段空间首地址,也就是第一个元素的地址,比如0*3000,赋给scores变量。该地址相当于一个指针,指向堆内存中分配的空间。此时堆内存中分配的5个空间可以分别使用scores[0],一直到scores[4]来表示。当执行四个赋值语句时,分别用指定值填充到对应元素位置。如果此时将null值赋给scores时,scores变量将不再指向任何位置,此时堆内存中分配的空间就变成了垃圾,由垃圾回收器在某一时间进行回收。
在方法中定义的变量,包括基本数据类型变量和引用数据类型变量,都将在栈内存中分配空间,当超过变量作用范围后,自动回收
我的总结:初始化=定义数组+分配空间+赋值
11、二维数组:
二维数组:(其实是一个一维数组,它的每一个元素又是一个一维数组),
可以看做是一张表格。
初始化:
动态初始化
int[ ][ ] arr = new int[3][2];
定义了一个二维数组,其中有3个一维数组,每一个一维数组中有2个元素
静态初始化
int[ ][ ] arr = new int[][]{{1,2},{3,4},{5,6}};
int[ ][ ] arr = {{1,2},{3,4},{5,6}};
Eg:
public class Demo3 {
public static void main(String[] args) {
int age[][] = new int[][]{{1,2},{3,4},{5,6,7}};
System.out.println(age[0].length);//2
System.out.println(age[2].length);//3
}
}
12、操作数组的工具类-Arrays
static int binarySearch(type[] a, type key) 使用二分搜索法来搜索key元素在数组中的索引;若a数组不包括key,返回负数。(该方法必须已按升序排列后调用)。
static int binarySearch(type[] a, int fromIndex, int toIndex, type key) 使用二分搜索法来搜索key元素在数组中从fromIndex到toIndex的索引;若a数组不包括key,返回负数。(该方法必须已按升序排列后调用)。
static boolean[] copyOf(type[] original, int newLength) 复制指定的数组见下面备注
static byte[] copyOfRange(type[] original, int from, int to) 将数组的指定范围复制到一个新数组。
static boolean equals(type[] a, type[] a2) 如果两个数组长度相等和元素一一相等,则返回 true
static void fill(type[] a, type val) 将a数组所有元素都赋为val。
static void fill(type[] a, int fromIndex, int toIndex, type val) 将a数组从formIndex 到tiondex索引之间的元素都赋为val。
static void sort(type[] a) //sort(int[] arr)对指定的数组按数字升序进行排序。
static void sort(type[] a, int fromIndex, int toIndex) 对指定数组的从formIndex 到tiondex索引之间的元素按数字升序进行排序。
static String toString(type[] a) 返回指定数组内容的字符串表示形式。多个数组元素之间用英文逗号或空格隔开。
我的总结:使用数组工具类可以节省时间,提高效率,注意常查阅api;
Eg:
package reviewDemo;
import java.util.Arrays;
//使用Arrays类
public class Demo4 {
public static void main(String[] args) {
int[] age = new int[] { 12, 26, 3, 60, 55, 6, 48, 4, 98 };
System.out.println(Arrays.toString(age));//直接打印出数组的方法
int []age2 = {1,2,3,4,5,6,98,65,23};
int i = Arrays.binarySearch(age2, 98);
System.out.println(i);
}
}
13、Java5新特性对数组的支持:
增强for循环 → for-each
for (参数类型 参数名 : 数组名) {
代码块
}
Eg:
package reviewDemo;
public class Demo6 {
public static void main(String[] args) {
int []age = {1,2,3,69,36,636,459};
for (int i : age) {
System.out.println(i);
}
}
}
这样就用for-each把数组遍历输出!
我的总结:for-each用于数组和Iterable对象!在以后的集合学习中还会经常用到for-each循环。