续java学习12:
1、数组,引用类型变量,保存数据实际是保存的数组的首地址
2、定义数组容器三要素,数据类型,大小(长度),数组名
3、数组的定义公式一:数据类型[] 数组名 = new 数据类型[元素个数或数组长度]
4、数组的定义公式二:数组类型[] 数组名 = new 数据类型[]{元素1,元素2,元素3,...} //不允许填写元素个数或数组长度,否者编译失败
5、数组的定义公式三:数组类型[] 数组名 = { 元素1 , 元素2 , ... }
6、数组中存储的每个元素,都有自己的自动编号,自动编号,最小值为0,最大值为长度-1,自动编号专业名称,索引(index),下标,角标,访问数组中的原属,必须依赖于索引,公式:数组名[索引]
java提供一个属性,操作索引:
数组的一个属性,就是数组的长度,属性的名字.length
使用属性:int len = 数组名.length 数据类型 int
数组的最小索引是0,最大索引是数组名.length-1
7、JVM对自己的内存进行了划分,分成5个区域
寄存器:内存和CPU之间
本地方法栈:JVM调用了系统中的功能
方法和数据共享:运行时期class文件,进入的地方
方法栈:所有的方法运行的时候,进入的内存
堆:存储的是容器和对象
8、示例代码
public class ArraryDemo {
public static void main ( String [] args ) {
//定义数组第一种方式,存储整数,容器长度,3个
int [] arr = new int [ 3 ] ;
System.out.println( arr ) ;
//通过索引的方式,数组中的三个元素
System.out.println( arr[ 0 ] ) ;
System.out.println( arr[ 1 ] ) ;
System.out.println( arr[ 2 ] ) ;
System.out.println( arr.length ) ;
//定义数组第二种方式
int [] arr2 = new int [] { 1 , 3 , 5 , 7 , 9 } ;
System.out.println( arr2[ 1 ] ) ;
System.out.println( arr2.length ) ;
//定义数组第三种方式
int [] arr3 = { 1 , 2 , 3 , 4 } ;
System.out.println( arr3[ 1 ] ) ;
System.out.println( arr3.length ) ;
}
}
9、数组元素赋值
/*
数组的操作,使用索引,对数组中的元素赋值
*/
public class ArrayDemo_1 {
public static void main ( String [] args ) {
int [] arr = new int [ 5 ] ;
System.out.println( arr [ 0 ] ) ; // 输出赋值前的值
arr [ 0 ] = 5 ; // 给数组元素赋值
System.out.println( arr [ 0 ] ) ; // 输出赋值后的值
}
}
10、数组遍历:{ 1 , 5 , 6 , 7 , 4 }
/*
数组遍历:{ 1 , 5 , 6 , 7 , 4 }
将所有的数组元素,全部输出
依靠索引,规律从0开始,一直自动增长1,到达length-1
通过循环来实现:
for 知道循环次数,计数器思想
while 不确定循环次数
*/
public class ArrayDemo_3 {
public static void main ( String [] args ) {
int [] arr = new int [] { 1 , 5 , 6 , 7 , 4 } ; // 创建数组
for ( int i = 0 ; i < arr.length ; i ++ ) {
System.out.println( arr[ i ] ) ; // 循环输出数组所有元素
}
}
}
11 、数组异常:A、数组的索引越界异常;B、空指针异常。
/*
数组操作中,常见的两个异常
1、数组的索引越界异常
2、空指针异常
*/
public class ArrayDemo_04 {
public static void main ( String [] args ) {
int [] arr = { 4 , 5 , 6 , 0 } ;
//数组索引越界异常
//System.out.println( arr [ 4 ] ) ; // java.lang.ArrayIndexOutOfBoundsException: 4
arr = null;
//数组空指针异常
System.out.println( arr [ 0 ] ) ; // java.lang.NullPointerException
}
}
12、找到数组{ 0 , 5 , 1 , 5 , 3 , 4 , 6 , 9 , 4 , 7 , 8 }中最大的数
/*
找到数组{ 0 , 5 , 1 , 5 , 3 , 4 , 6 , 9 , 4 , 7 , 8 }中最大的数
*/
public class ArrayDemo_05 {
public static void main ( String [] args ) {
int [] arr = { 0 , 5 , 1 , 5 , 3 , 4 , 6 , 9 , 4 , 7 , 8 } ; // 定义整型数组
int max = arr [ 0 ] ; // 将数组中第一个值赋给max
//采用for循环
for ( int i = 1 ; i < arr.length ; i ++ ) {
if ( max < arr [ i ] ) {
max = arr [ i ] ; // 将大于max的值赋给max
}
}
System.out.println( max ) ; // 输出数组中最大值
}
}
13、 二维数组:定义方式和一维数组相似
例如:
方式一:int [] [] arr = new int [ 3 ] [ 4 ] ;
方式二:int [] [] arr = new int [ 3 ] [] ;
待续...