数组的常见操作

数组越界异常

观察一下代码,运行后会出现什么结果。

 public static void main(String[] args) {
     int[] arr = {1,2,3};
     arr = null;
     System.out.println(arr[0]);    
} 

arr = null 这行代码,意味着变量arr将不会在保存数组的内存地址,也就不允许再操作数组了,因此运行的时候会抛出 NullPointerException 空指针异常。在开发中,数组的越界异常是不能出现的,一旦出现了,就必须要修改我们编写的代码。 

 

空指针异常在内存图中的表现

 

 数组遍历【重点】

数组遍历: 就是将数组中的每个元素分别获取出来,就是遍历。遍历也是数组操作中的基石。

 public static void main(String[] args) {
    int[] arr = { 1, 2, 3, 4, 5 };  
    System.out.println(arr[0]);  
    System.out.println(arr[1]);  
    System.out.println(arr[2]);  
    System.out.println(arr[3]);  
    System.out.println(arr[4]);
}

以上代码是可以将数组中每个元素全部遍历出来,但是如果数组元素非常多,这种写法肯定不行,因此我们需要改造成循环的写法。数组的索引是 0 到 lenght-1 ,可以作为循环的条件出现。  

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

 

 

 

数组获取最大值元素

最大值获取:从数组的所有元素中找出最大值。

实现思路:

定义变量,保存数组0索引上的元素
遍历数组,获取出数组中的每个元素
将遍历到的元素和保存数组0索引上值的变量进行比较如果数组元素的值大于了变量的值,变量记录住新的值数组循环遍历结束,变量保存的就是数组中的最大值

public static void main(String[] args) {
	int[] arr = { 5, 15, 2000, 10000, 100, 4000 };
	// 定义变量,保存数组中0索引的元素
	int max = arr[0];
	// 遍历数组,取出每个元素
	for (int i = 0; i < arr.length; i++) {
		// 遍历到的元素和变量max比较
		// 如果数组元素大于max
		if (arr[i] > max) {
			// max记录住大值
			max = arr[i];
		}
	}
     System.out.println("数组最大值是:"+max); }

  

数组反转

数组的反转: 数组中的元素颠倒顺序,例如原始数组为1,2,3,4,5,反转后的数组为5,4,3,2,1

实现思想:数组最远端的元素互换位置。

  • 实现反转,就需要将数组最远端元素位置交换
  • 定义两个变量,保存数组的最小索引和最大索引两个索引上的元素交换位置
  • 最小索引++,最大索引--,再次交换位置
  • 最小索引超过了最大索引,数组反转操作结束

 

 

 

public static void main(String[] args) {
	int[] arr = { 1, 2, 3, 4, 5 };
	/*
	 * 循环中定义变量min=0最小索引 max=arr.length-1最大索引 min++,max--
	 */
	for (int min = 0, max = arr.length - 1; min <= max; min++, max--) {
		// 利用第三方变量完成数组中的元素交换
		int temp = arr[min];
		arr[min] = arr[max];
		arr[max] = temp;
	}

	// 反转后,遍历数组
	for (int i = 0; i < arr.length; i++) {
		System.out.println(arr[i]);
	}
}

  

 

posted @ 2019-01-05 21:45  竹子の云  阅读(152)  评论(0)    收藏  举报