数组
数组(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]); //生成java基础数组对象之后,引用指向对象 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];
如下程序:
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
总结
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/10868.html