1.数组的概念
数组:是一种特殊的集合,是一种特殊的容器
特殊:
1、数组中只能存储相同的类型的元素。
2、数组的存储空间是连续的
3、数组的长度是固定的,而且是不可改变的
2.数组的定义
元素类型[] 变量 = new 元素类型[数组的长度];String[] names2 = {"张三","王五","李四"};
3.数组的使用
数组是按照下标来完成使用的
下标从0开始,到 数组的长度-1 结束,如果在使用时,超过了该范围,将抛出
java.lang.ArrayIndexOutOfBoundsException
4.数组的长度
5.数组的遍历
5.1for循环
//遍历数组方式1for(int i = 0; i <= length -1; i ++) {System.out.println(names[i]);}
5.2foreach
//foreach for的增强for (String str : names) {System.out.println(str);}
6.数组的复制
6.1新数组遍历复制
//假设,我还有元素, 需要向nums 中进行填充 ,如何办?int[] newArr = new int[10];int lenth = nums.length;for(int i = 0; i < lenth; i ++) {newArr[i] = nums[i];
6.2 System.arraycopy()
//假设,我还有元素, 需要向nums 中进行填充 ,如何办?int[] newArr = new int[10];System.arraycopy(nums, 0, newArr, 0, nums.length);newArr[5] = 21;
nums 表示源数组
0 表示源数组需要复制元素的起始位置
newArr 表示目标数组
0 表示目标数组可以设置元素的起始位置
nums.length 表示源数组中可以复制的元素的个数
6.3Arrays(最优)
int[] newArr = Arrays.copyOf(nums, 10);newArr[5] = 21;
7.多维数组
7.1 二维数组(行列)
public class MultiArray {public static void main(String[] args) {// TODO Auto-generated method stub//一维String[] str = {"张三","李四","王五"};//如果要遍历一维数组,只需要1个for即可完成//二维(使用场景:电影院 买票选座)String[][] names = new String[3][3];int lenth = names.length;// System.out.println(lenth);for(int i = 0; i < lenth; i ++) {String[] strs = names[i];int lenth02 = strs.length;for(int j = 0; j < lenth02; j ++) {names[i][j] = i * j + "";}}//输出// System.out.println(Arrays.toString(names));for(int i = 0; i < lenth; i ++) {String[] strs = names[i];int lenth02 = strs.length;for(int j = 0; j < lenth02; j ++) {System.out.print(names[i][j] + " ");}System.out.println();}//三维数组同理,它在装或取时,就需要3个嵌套循环
7.2 三维数组(xyz)
同上
