首页 / 软件开发 / JAVA / 数组在Java编程中的应用
数组在Java编程中的应用2010-12-08序数组是很重要的数据结构,由同一类型相关的数据结构组成是静态实体,有链 表,队列,堆栈,数等数据结构,java还提出了类数组的类vector。这些都是java数 据结构的组成部分,正如我们学过的c语言版的数据结构,java数据结构也是来描 述数据结构的只是描述语言是java一样而已。1.数组中最重要的是数组下标,数组下标及数组名是用来给访问者提供访问 数组的途径,数据下标从0开始,c[0],就是一个第一个数据第一个元素是c[i- 1],数组名的名名规则与变量相同,其访问格式也很简单。例:c.lenth就是数组的长度。c[a+b]+=2 就是个数组a+b的值+2,在此数组也有易混淆的地方,那就是数组 的第7个元素和数组元素7是两个不相同的概念,初学者一定要区分其区别。2.空间分配:任何数据都要占用空间,数组也不例外,java中用new来给一个 新的数组分配空间。例:int c[ ]=new int[12];
其格式等同于int c[];
c=new int[12];
他们的初始化值都是0。一个数组可以同时声明多个数组:例:string b[ ]=new String[100],x[ ]=new String[27];
数组可以声明任何数据类型,double string ..举个例子来分析:// Fig. 7.5: InitArray.java
// initialize array n to the even integers from 2 to 20
import javax.swing.*;
public class InitArray {
public static void main( String args[] )
{
final int ARRAY_SIZE = 10;
int n[]; // reference to int array
String output = "";
n = new int[ ARRAY_SIZE ]; // allocate array
// Set the values in the array
for ( int i = 0; i < n.length; i++ )
n[ i ] = 2 + 2 * i;
output += "Subscript Value
";
for ( int i = 0; i < n.length; i++ )
output += i + " " + n[ i ] + "
";
JTextArea outputArea = new JTextArea( 11, 10 );
outputArea.setText( output );
JOptionPane.showMessageDialog( null, outputArea,
"Initializing to Even Numbers from 2 to 20",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}