• Java 基础(Arrays工具类的使用, 数组中的常见异常)


    java.util.Arrays类即为操作数组的工具类,包含了用来操作数组(比如搜索和排序)的各种方法

    序号 方法 说明
    1 boolean equals(int[] a, int[] b) 判断连个数组是否相等
    2 String toString(Int[] a) 输出数组的信息
    3 void fill(int[] a, int val) 将指定值填充到数组之中
    4 void sort(int[] a) 对数组进行排序
    5 int binarySearch(int[] a, int key) 对排序后的数组进行二分法检索指定的值
    import java.util.Arrays;
    
    public class ArraysTest {
    	public static void main(String[] args) {
    		//1.判断两个数组是否相等
    		int[] arr1 = new int[]{1, 2, 3, 4};
    		int[] arr2 = new int[]{1, 3, 2, 4};
    		boolean isEquals = Arrays.equals(arr1, arr2);
    		System.out.println(isEquals);    //false
    		
    		//2.输出数组的信息
    		System.out.println(Arrays.toString(arr1));
    		
    		//3.把指定的值填充到数组之中
    		Arrays.fill(arr1, 10);
    		System.out.println(Arrays.toString(arr1));
    		
    		//4.对数组进行排序
    		Arrays.sort(arr2);
    		System.out.println(Arrays.toString(arr2));
    		
    		//5.二分法查找
    		int[] arr3 = new int[] {-98, -34, 2, 34, 54, 78, 79, 106, 210, 333};
    		int index = Arrays.binarySearch(arr3, 210);
    		if(index >= 0) {
    			System.out.println(index);
    		}else {
    			System.out.println("未找到~");
    		}
    		
    	}
    
    }
    

    数组中的常见异常

    1. 数组角标越界异常:ArrayIndexOutOfBoundsException
    public class ArrayExecptionTest {
    	public static void main(String[] args){
    		int[] arr = new int[]{1, 2, 3, 4, 5};
    		
    		for(int i = 0; i <= arr.length; i++) {
    			System.out.println(arr[i]);
    		}
    		
    		//System.out.println(arr[-2]);   //同样报错         
    	}
    
    }
    

    2.空指针异常: NullPointerException

    public class ArrayExecptionTest {
    	public static void main(String[] args){
    		//情况一:
    		//int[] arr1 = new int[]{1, 2, 3};
    		//arr1 = null;
    		//System.out.println(arr1[0]); //Exception in thread "main" java.lang.NullPointerException: Cannot load from int array because "arr1" is null
    
                    //情况二:
    		//int[][] arr2 = new int[4][];
    		//System.out.println(arr2[0][0]);  //Exception in thread "main" java.lang.NullPointerException: Cannot load from int array because "arr2[0]" is null
                      
                    //情况三:
    		String[] arr3 = new String[]{"AA", "BB", "CC"};
    		arr3[0] = null;
    		System.out.println(arr3[0].toString()); //Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toString()" because "arr3[0]" is null
    
    	}
    
    }
    
    
    
    
  • 相关阅读:
    J2ME 游戏开发之GameCanvas的使用
    J2ME游戏开发之字符串的绘制
    JS数组操作
    什么是LBS?地理位置服务
    js中的this怎么理解
    相机参数
    boost 移植到ARM EP9315
    armlinuxgcc 安装和配置
    小算法 : 水仙花数
    C语言标准库 文件操作
  • 原文地址:https://www.cnblogs.com/klvchen/p/14292442.html
Copyright © 2020-2023  润新知