﻿ Java自学第三讲|数组 - 鸿网互联

# Java自学第三讲|数组

Java自学第三讲|数组 1.一维数组的声明方式 package zixue ; public class ZX1 { public static void main ( String [] args ) { int [] a ; //声明，方括号可以写到后面，像C++一样 double [] b ; Student [] c ; //对象数

### Java自学第三讲|数组

#### 1.一维数组的声明方式

package zixue;
public class ZX1{
public static void main(String[] args) {
int[] a; //声明，方括号可以写到后面，像C++一样
double[] b;
Student[] c; //对象数组
}
}
class Student{
int age;
public void sayHello() {
System.out.println("Hello!" + age);
}
}

Java语言中声明数组时不能指定其长度（这里要区别于C++），同时这里也体现了Java语言的稳定性。

#### 2.数组初始化

public class ZX1{
public static void main(String[] args) {
int[] a = new int[3];
a[0] = 3;a[1] = 2;a[2] = 3;
Student[] b = new Student[3];
b[0] = new Student(1);
b[1] = new Student(2);
b[2] = new Student(3);
}
}
class Student{
int age;
public Student(int n) {
age = n;
}
}

package zixue;
public class ZX1{
public static void main(String[] args) {
int[] a = {3,2,1};
int[] b = new int[] {1,2,3};
Student[] s = {
new Student(1),
new Student(2),
new Student(3)
};
}
}
class Student{
int age;
public Student(int n) {
age = n;
}
}

#### 3.数组元素的引用

public class ZX1{
public static void main(String[] args) {
int[] a = {3,2,1};
System.out.println(a[0]);
int i = 1;
System.out.println(a[i]);
System.out.println(a[i * 2]);
}
}

public class ZX1{
public static void main(String[] args) {
int[] a = {1,5,3};
for(int i = 0;i < a.length;++i)
System.out.println(a[i]);
}
}

#### 4.增强的for语句

public class ZX1{
public static void main(String[] args) {
int[] a = {1,5,3};
for(int i : a)
System.out.println(i);
}
}

#### 5.复制数组

public class ZX1{
public static void main(String[] args) {
int[] a = {1,5,3};
int[] b = {2,3,4,5,6};
System.arraycopy(a, 0, b, 0, a.length);
for(int i : b)
System.out.println(i);
}
}

System.arraycopy(a,0,b,0,a.length)表示将数组a从0(第一个)开始的数赋值给数组b从0(第二个)开始的位置,赋值的个数是a.length,此程序执行结果是:

1
5
3
5
6

#### 6.多维数组

public class ZX1{
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];
}
}

Java自学第三讲部分总结。

<