当前位置:网站首页 > Java基础 > 正文

数组基础java



数组

数组(Array):相同类型数据的集合。

Java 数组初始化的两种方法:

数组是否必须初始化

定义数组

  方式1(推荐,更能表明数组类型)
  type[] 变量名 = new type[数组中元素的个数];
  比如:

  int[] a = new int[10];

  如:

 int a[] = new int[10];

  其中红色部分可省略,所以又有两种:

   int[] a = {1,2,3,4};   int[] a = new int[]{1,2,3,4};

  如下程序:

 public class ArrayTest { public static void main(String[] args) { int[] a = {1, 2, 3}; int[] b = {1, 2, 3}; System.out.println(a.equals(b)); } }

  代码如下:

 ArrayEqualsTest.java import java.util.Arrays; public class ArrayEqualsTest { //Compare the contents of two int arrays public static boolean isEquals(int[] a, int[] b) { if( a == null || b == null ) { return false; } if(a.length != b.length) { return false; } for(int i = 0; i < a.length; ++i ) { if(a[i] != b[i]) { return false; } } return true; } public static void main(String[] args) { int[] a = {1, 2, 3}; int[] b = {1, 2, 3}; System.out.println(isEquals(a,b)); System.out.println(Arrays.equals(a,b)); } }

  如下列程序:

 ArrayTest2.java public class ArrayTest2 { public static void main(String[] args) { Person[] p = new Person[3]; //未生成对象时,引用类型均为空 System.out.println(p[0]); //生成对象之后,引用指向对象 p[0] = new Person(10); p[1] = new Person(20); p[2] = new Person(30); for(int i = 0; i < p.length; i++) { System.out.println(p[i].age); } } } class Person { int age; public Person(int age) { this.age = age; } }

  null
  10
  20
  30

  也可以在初始化列表里面直接写:

 Person[] p = new Person[]{new Person(10), new Person(20), new Person(30)};

  type[][] i = new type[2][3];(推荐)
  type i[][] = new type[2][3]; 数组基础java

  如下程序:

 public class ArrayTest3 { public static void main(String[] args) { int[][] i = new int[2][3]; System.out.println("Is i an Object? " + (i instanceof Object)); System.out.println("Is i[0] an int[]? " + (i[0] instanceof int[])); } }

  如下程序:

 public class ArrayTest4 { public static void main(String[] args) { //二维变长数组 int[][] a = new int[3][]; a[0] = new int[2]; a[1] = new int[3]; a[2] = new int[1]; //Error: 不能空缺第一维大小 //int[][] b = new int[][3]; } }

  如下程序:

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

  1 2 3
  4
  5 6 7 8

总结

  • 上一篇: java基础不懂
  • 下一篇: 74期java基础
  • 版权声明


    相关文章:

  • java基础不懂2025-04-04 11:42:05
  • java集合基础题2025-04-04 11:42:05
  • java画画基础2025-04-04 11:42:05
  • java 基础数据类2025-04-04 11:42:05
  • java基础反射视频2025-04-04 11:42:05
  • 74期java基础2025-04-04 11:42:05
  • java基础补贴2025-04-04 11:42:05
  • java运维基础2025-04-04 11:42:05
  • java基础继承题2025-04-04 11:42:05
  • java基础银行存取款2025-04-04 11:42:05