"数组"是一种很基础但又极为重要的数据结构。几乎所有的编程语言对数组操作提供了支持。 Java中的数组既拥有数组普遍的特性: 比如按下标访问,元素连续存放等,也有它自己的特色,比如使用一维数组实现多维数组,数组可以是不整齐的等等。
本讲围绕“数组”这一核心内容而展开,重点是**引用类型数组的内存布局模型**。
本讲还包容了不少与数据结构相关的练习,完成它们,不仅可以训练自己的Java编程技能,同时还对数据结构的学习有一定的促进作用。事实上,在后面的课程中还会遇到不少与数据结构相关的内容,甚至有些数据结构的教材,就是以Java作为编程实现语言的。
int c[]= new int[12];
//相当于
int c[];//声明数组变量,declare array
c = new int[12];//分配内存空间,allocate array
String b[] = new String[100];
int n[]={1,2,3,4,5};
import javax.swing.*;
public class welcome1
{
public static void main(String[] args)
{
String output = "";
// Initializer list specifies number of elements and
// value for each element.
int n[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
output += "Subscript\tValue\n";
for ( int i = 0; i < n.length; i++ )
output += i + "\t" + n[ i ] + "\n";
//这里先把头部的两个标志写入output,然后再依次把行号和真正数据写入output,为下面的数据识别做准备
JTextArea outputArea = new JTextArea( 11, 10 );
outputArea.setText( output );
JOptionPane.showMessageDialog( null, outputArea,
"Initializing an Array with a Declaration",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
myclass [] arr = new myclass[12];
arr[7].value = 32;
//运行时引发java.lang.NullPointerException,因为尝试访问一个还不存在的对象,是一种常见的错误
public static void main()
{
Object[] arr ={"a","b",13};
System.out.println(arr);
}
上述代码可以通过编译,但是输出的数值有些奇怪
int [] a = new int [100];
for(int i=0;i<a,length;i++)
{
System.out.println(a[i]);
}
int[] num=new int[100];
for(int element:nums)
System.out.println(element);
int[][] a;
a = new int[3][];
for (int i = 0; i < a.length ; i++ )
{
System.out.println(a[i]);//null
}
a[0] = new int[2];
a[0][0] = 1;
a[0][1] = 2;
for (int i = 0 ; i < a[0].length ; i ++ )
{
System.out.println(a[0][i]);//1 2!
}
int[] from = {0,1,2,3,4,5,6,7,8,9,};
int[] to = new int [10];
System.arraycopy(from,5,to,4,2);
for(int element:to )
System.out.println(element);
第一个参数是原数组
第二个是原数组开始复制的起点下标
第三个参数是目标数组
第四个参数是目标数组待复制的起始位置
第五个参数是要复制多少个在目标数组里