为什么会发生 ArrayIndexOutOfBoundsException 以及如何在 Android 中避免它? [英] Why does ArrayIndexOutOfBoundsException occur and how to avoid it in Android?

查看:32
本文介绍了为什么会发生 ArrayIndexOutOfBoundsException 以及如何在 Android 中避免它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会出现ArrayIndexOutOfBoundsException以及在Android中如何避免?

Why does ArrayIndexOutOfBoundsException occur and how to avoid it in Android?

推荐答案

当您尝试访问不存在的数组项时抛出此异常:

This exception is thrown when you try to access an array item that doesn't exist:

String [] myArray = new String[2];

myArray[2] = "something"; // Throws exception
myArray[-1] = "something"; // Throws exception

在访问数组项之前,您应该检查索引是否为负且不大于数组长度.

You should check that your index is not negative and not higher than the array length before accessing an array item.

这篇关于为什么会发生 ArrayIndexOutOfBoundsException 以及如何在 Android 中避免它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆