声明方式

  1. type[] arr_name; //(推荐使用这种方式)
  2. type arr_name[];
  1. public class Test {
  2. public static void main(String args[]) {
  3. int[] s = null; // 声明数组;
  4. s = new int[10]; // 给数组分配空间;
  5. for (int i = 0; i < 10; i++) {
  6. s[i] = 2 * i + 1;//给数组元素赋值;
  7. System.out.println(s[i]); //数组输出
  8. }
  9. // System.out.println(Arrays.toString(c)); 数组输出
  10. }
  11. }

for-each循环

专门用于读取数组或集合中所有的元素,即对数组进行遍历。

  1. public class Test {
  2. public static void main(String[] args) {
  3. String[] ss = { "aa", "bbb", "ccc", "ddd" };
  4. for (String temp : ss) { //循环遍历数组ss 把每个元素放入temp中输出
  5. System.out.println(temp);
  6. }
  7. }
  8. }

数组拷贝

  1. static void arraycopy(object srcint srcposobject dest int destposint length)

该方法可以将src数组里的元素值赋给dest数组的元素,其中srcpos指定从src数组的第几个元素开始赋值,destpos指定拷贝到目标的第几个位置,length参数指定将src数组的多少个元素赋给dest数组的元素

  1. public class TextArraycpy {
  2. public static void main(String[] args) {
  3. String s1[] = {"a","b","c","d","e"};
  4. String s2[] = new String[5];
  5. System.arraycopy(s1, 2, s2, 0, 3);
  6. for (String s11 : s2) {
  7. System.out.print(s11+" ");
  8. }
  9. }
  10. }
  11. //输出:c d e null null

数组的扩容和数组的删除

实际也是数组的拷贝做原理

  1. //删除某个数组元素(本质是数组自身的拷贝)
  2. public static void del() {
  3. String s1[] = {"a","b","c","d","e"};
  4. System.arraycopy(s1, 3, s1, 2, 2);
  5. s1[s1.length -1] = null;
  6. for (String m : s1) {
  7. System.out.print(m+" ");
  8. }
  9. }
  10. //数组扩容(本质是定义一个更大的数组 再把原数组拷贝到新数组内)
  11. public static void extend() {
  12. String s1[] = {"a","b","c","d","e"};
  13. String s2[] = new String[s1.length+5];
  14. System.arraycopy(s1, 0, s2, 0, s1.length);
  15. for (String m : s2) {
  16. System.out.print(m+" ");
  17. }
  18. }

java.util.Arrays类

包含了常用的数组操作,方便开发。Arrays类包含了:排序、查找、填充、打印内容等常见的操作

  1. import java.util.Arrays;
  2. public class Test {
  3. public static void main(String args[]) {
  4. int a[] = { 1, 12 };
  5. Arrays.sort(a); //数组的排序
  6. System.out.println(Arrays.binarySearch(a, 12)); //array里面的二分查找
  7. System.out.println(Arrays.toString(a)); // 打印数组元素的值;
  8. int[] arr2 = new int[5];
  9. Arrays.fill(arr2,2,4, 100); //数组的填充
  10. System.out.println(Arrays.toString(arr2));
  11. }
  12. }

多维数组

声明

  1. public class Test {
  2. public static void main(String[] args) {
  3. //Java中多维数组的声明和初始化应按从低维到高维的顺序进行
  4. int a[][] = new int[3][]; //把数组看成对象存入一维数组
  5. a[0] = new int[2];
  6. a[1] = new int[4];
  7. a[2] = new int[3];
  8. // int a1[][]=new int[][4];非法
  9. }
  10. }
  1. public class TextArrayTab {
  2. public static void main(String[] args) {
  3. //数组存储表格数据
  4. Object[] temp1 = {1000,"H",20,"adc"};
  5. Object[] temp2 = {1001,"G",21,"dc"};
  6. Object[] temp3 = {1002,"F",22,"ac"};
  7. Object tabledata[][] = new Object[3][];
  8. tabledata[0] = temp1;
  9. tabledata[1] = temp2;
  10. tabledata[2] = temp3;
  11. for(Object[] temp: tabledata) {
  12. System.out.println(Arrays.toString(temp));
  13. }
  14. }
  15. }