文档介绍:Java程序设计
Java Programming
Spring, 2013
1
成都信息工程学院计算机系
Contents
Arrays(数组)
2
Chapter 4 Java Basic Grammar
Arrays (数组)
An array is a collection of data values, all of which have the same type.
Components:
Primitive types or reference to objects
Arrays are objects in Java(数组是一种特殊的对象)
(声明)
(分配内存空间) : new
3. 释放(Java虚拟机完成)
3
Chapter 4 Java Basic Grammar
Declaring Arrays(声明数组)
An array variable is declared with the type of its members.
一维数组的声明
方法2: 类型[] 数组名;
String[] args;
int[] a;
double[] amount;
char[] c;
方法1: 类型数组名[];
String args[];
int a[];
double amount[];
char c[];
4
Chapter 4 Java Basic Grammar
Declaring Arrays(声明数组)
注意:
数组类型是数组中元素的数据类型;
数组名是一个标识符;
When an array variable is declared, the array is NOT created. What we have is only a name of an array.
5
Chapter 4 Java Basic Grammar
Creating Arrays(创建数组)
创建数组:为数组元素分配内存空间,并对数组元素进行初始化
To create the array, operator new is used.
We must provide the number of members in the array, and the type of the members. These cannot be changed later.
格式: 数组名= new 数据类型[数组长度]
Example:
or, combining the declaration and the array creation:
double[] anArray;
anArray = new double[5];
double[] anArray = new double[5];
6
Chapter 4 Java Basic Grammar
Creating Arrays(创建数组)
double[] anArray ; //declare
anArray = new double[3]; //create
anArray:
?
?
?
length
3
0
1
2
anArray:
null
Here, the array is
not defined.
Here, the array is
defined, but the
elements in the array
are NOT defined.
7
Chapter 4 Java Basic Grammar
Creating Arrays(创建数组)
默认赋初值
整型初值为0
int[] i = new int[3];
实型
float[] f = new float[3];
布尔型初值为false
boolean[] b = new boolean[3];
字符型初值为\u0000(null)
char[] c = new char[3];
8
Chapter 4 Java Basic Grammar
Accessing(访问) array members
Array members are accessed by indices(下标) using the subscript operator []. The indices are integers starting from 0.
In Java, for an array of length n, the values in the array are indexed from 0 up to n – 1.
If an inde