首页 > 编程语言 >ArrayIndexOutOfBoundException and NegativeArraySizeException in Java

ArrayIndexOutOfBoundException and NegativeArraySizeException in Java

时间:2024-03-21 12:11:27浏览次数:31  
标签:ArrayIndexOutOfBoundsException index java int ArrayIndexOutOfBoundException Nega

ArrayIndexOutOfBoundException

ArrayIndexOutOfBoundsException occurs when we access an array, or a Collection, that is backed by an array with an invalid index. This means that the index is either less than zero or greater than or equal to the size of the array.

  • 也就是说,使用 index 索引数组的时候可能出现了负数或者是大于数组长度的数

可能出错的情况

越界访问数组

Accessing the array elements out of these bounds would throw an ArrayIndexOutOfBoundsException:

int[] numbers = new int[] {1, 2, 3, 4, 5};
int lastNumber = numbers[5];

Here, the size of the array is 5, which means the index will range from 0 to 4.
In this case, accessing the 5th index results in an ArrayIndexOutOfBoundsException:

Here, the size of the array is 5, which means the index will range from 0 to 4.

In this case, accessing the 5th index results in an _ArrayIndexOutOfBoundsException_:
访问由 Arrays.asList() 返回的 List

If we try to access the elements of the List returned by Arrays.asList() beyond this range, we would get an ArrayIndexOutOfBoundsException:

List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5);
int lastNumber = numbersList.get(5);

Here again, we are trying to get the last element of the List. The position of the last element is 5, but its index is 4 (size – 1). Hence, we get ArrayIndexOutOfBoundsException as below:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4351)
    at  ...
循环遍历数组

Sometimes, while iterating over an array in a for loop, we might put a wrong termination expression.

Instead of terminating the index at one less than the length of the array, we might end up iterating until its length:

int sum = 0;
for (int i = 0; i <= numbers.length; i++) {
    sum += numbers[i];
}

In the above termination expression, the loop variable i is being compared as less than or equal to the length of our existing array numbers. So, in the last iteration, the value of i will become 5.

Since index 5 is beyond the range of numbers, it will again lead to ArrayIndexOutOfBoundsException:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    at com.baeldung.concatenate.IndexOutOfBoundExceptionExamples.main(IndexOutOfBoundExceptionExamples.java:22)

Avoid This Exception

  • Remembering the index
  • Correctly Using the Operators in Loops
  • Using Enhanced for Loops (using iterator)

NegativeArraySizeException

什么导致了NegativeArraySizeException in Java

The NegativeArraySizeException occurs when an attempt is made to assign a negative size to an array. Here's an example:

public class NegativeArraySizeExceptionExample {
    public static void main(String[] args) {
        int[] array = new int[-5];
        System.out.println("Array length: " + array.length);
    }
}

Running the above code throws the following exception:

Exception in thread "main" java.lang.NegativeArraySizeException: -5
    at NegativeArraySizeExceptionExample.main(NegativeArraySizeExceptionExample.java:3)

怎么解决 NegativeArraySizeException in Java

The NegativeArraySizeException can be handled in code using the following steps:

  • Surround the piece of code that can throw an NegativeArraySizeException in a try-catch block.
  • Catch the NegativeArraySizeException in the catch clause.
  • Take further action as necessary for handling the exception and making sure the program execution does not stop.

Here's an example of how to handle it in code:

public class NegativeArraySizeExceptionExample {
    public static void main(String[] args) {
        try {
            int[] array = new int[-5];
        } catch (NegativeArraySizeException nase) {
            nase.printStackTrace();
            //handle the exception
        }
        System.out.println("Continuing execution...");
    }
}

In the above example, the lines that throw the NegativeArraySizeException are placed within a try-catch block. The NegativeArraySizeException is caught in the catch clause and its stack trace is printed to the console. Any code that comes after the try-catch block continues its execution normally.

Running the above code produces the following output:

java.lang.NegativeArraySizeException: -5
    at NegativeArraySizeExceptionExample.main(NegativeArraySizeExceptionExample.java:4)
Continuing execution...

怎么避免 NegativeArraySizeException in Java

Since the NegativeArraySizeException occurs when an array is created with a negative size, assigning a positive size to the array can help avoid the exception. Applying this to the earlier example helps fix the issue:

public class NegativeArraySizeExceptionExample {
    public static void main(String[] args) {
        int[] array = new int[5];
        System.out.println("Array length: " + array.length);
    }
}

The array is initialized with a size of 5, which is a positive number. Running the above code produces the correct output as expected:

Array length: 5

reference:

标签:ArrayIndexOutOfBoundsException,index,java,int,ArrayIndexOutOfBoundException,Nega
From: https://www.cnblogs.com/Phantasia/p/18087086

相关文章

  • Java 8 内存管理原理解析及内存故障排查实践
    作者:vivo互联网服务器团队- ZengZhibin介绍Java8虚拟机的内存区域划分、内存垃圾回收工作原理解析、虚拟机内存分配配置,介绍各垃圾收集器优缺点及场景应用、实践内存故障场景排查诊断,方便读者面临内存故障时有一个明确的思路和方向。一、背景Java是一种流行的编程语言,可......
  • Java基础内容:第七章面向对象(下)编程题详解
            建了一个群:908722740 ,欢迎小伙伴门的加入,平时可以互相学习交流,不管是学习还是工作上的都可以多多交流,本人在校学生,技术有限,错误的地方欢迎指正。目录一、多态案例素材【1】乐手弹奏乐器【2】比萨制作【3】购买饮料二、接口案例素材【1】兔子和青蛙【......
  • Java 面向对象编程进阶四(多态、抽象方法抽象类)
    目录多态(polymorphism)多态和类型转换对象的转型(casting) 类型转换异常向下转型中使用instanceof final关键字抽象方法和抽象类抽象类和抽象方法的基本用法多态(polymorphism)        多态指的是同一个方法调用,由于对象不同可能会有不同的行为。现实......
  • 【设计模式】Java 设计模式之责任链模式(Chain of Responsibility)
    责任链模式(ChainofResponsibility)一、概述责任链模式是一种行为设计模式,它允许请求在对象链中传递。每个对象都有机会处理该请求,并且能将其传递给链中的下一个对象。这种模式为请求创建了一个处理对象的链,并沿着这条链传递该请求,直到有一个对象处理它为止。二、模式结......
  • 【设计模式】Java 设计模式之状态模式(State)
    深入理解状态模式(State)一、概述状态模式是一种行为设计模式,它允许一个对象在其内部状态改变时改变它的行为。对象看起来好像修改了它的类。状态模式把所有的与一个特定的状态相关的行为放到一个类中,并且将请求委托给当前状态对象来执行。在状态模式中,我们创建表示各种状......
  • Java 面向对象编程进阶六(内部类 )
    目录内部类内部类的概念内部类的分类1、非静态内部类(外部类里使用非静态内部类和平时使用其他类没什么不同)2、静态内部类3、匿名内部类4、局部内部类内部类        内部类是一类特殊的类,指的是定义在一个类的内部的类。实际开发中,为了方便的使用外部类的相......
  • Java 面向对象编程进阶七(字符串 String )
    目录字符串StringString基础String类和常量池String类常用的方法String类常用方法一String类常用方法二字符串相等的判断字符串String        String是我们开发中最常用的类,我们不仅要掌握String类常见的方法,对于String的底层实现也需要掌握好......
  • 一文彻底搞懂令人疑惑的Java和JDK的版本命名!
    你对Java的版本号以及JDK的命名真正清楚嘛?比如:Java8JavaSE8.0JDK1.8……知道这些是怎么回事嘛?知道还有个Java2的说法嘛?知道还有以下说法嘛?J2SE1.3J2SE1.4……现在已经6月份了,到了9月份,一个新的长期支持版本,Java17就要发布了,啥?Java版本都到17了?不不不,我一直在用JDK......
  • 基于java+springboot+vue实现的电影院选票系统(文末源码+Lw+ppt)23-467
    摘要时代在飞速进步,每个行业都在努力发展现在先进技术,通过这些先进的技术来提高自己的水平和优势,电影院选票系统当然不能排除在外。电影院选票系统是在实际应用和软件工程的开发原理之上,运用java语言,前台Vue框架以及后台SpringBoot框架进行开发。首先要进行需求分析,分析出电......
  • 基于java+springboot+vue实现的智慧养老院管理系统(文末源码+Lw+ppt)23-490
    摘 要智慧养老院管理系统采用B/S架构,数据库是MySQL。网站的搭建与开发采用了先进的java进行编写,使用了springboot框架。该系统从三个对象:由管理员和家属、护工来对系统进行设计构建。主要功能包括:个人信息修改,对家属信息、护工信息、老人入住、外出报备、退房登记、每月餐饮......