是什么导致java.lang.arrayindexoutofboundsexception以及如何防止它?

ozxc1zmp  于 2021-07-03  发布在  Java
关注(0)|答案(17)|浏览(453)

是什么 ArrayIndexOutOfBoundsException 我的意思是我该怎么摆脱它?
下面是触发异常的代码示例:

String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {
    System.out.println(names[i]);
}
ioekq8ef

ioekq8ef16#

在代码中,您访问了从索引0到字符串数组长度的元素。 name.length 给出字符串对象数组中字符串对象的数目,即3,但最多只能访问索引2 name[2] ,因为可以从索引0到 name.length - 1 你去哪了 name.length 对象数。
即使在使用 for 循环以索引0开始,应该以 name.length - 1 . 在数组a[n]中,可以从a[0]访问a[n-1]。
例如:

String[] a={"str1", "str2", "str3" ..., "strn"};

for(int i=0; i<a.length(); i++)
    System.out.println(a[i]);

就你而言:

String[] name = {"tom", "dick", "harry"};

for(int i = 0; i<=name.length; i++) {
    System.out.print(name[i] +'\n');
}
iqih9akk

iqih9akk17#

对于看似神秘的arrayindexoutofboundseceptions(即显然不是由您自己的数组处理代码引起的),我见过的最常见的情况是并发使用simpledateformat。特别是在servlet或控制器中:

public class MyController {
  SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

  public void handleRequest(ServletRequest req, ServletResponse res) {
    Date date = dateFormat.parse(req.getParameter("date"));
  }
}

如果两个线程同时输入simplatedateformat.parse()方法,您可能会看到arrayindexoutofboundsexception。注意simpledateformat类javadoc的同步部分。
确保在您的代码中没有以servlet或控制器等并发方式访问simpledateformat之类的线程不安全类的地方。检查servlet和控制器的所有示例变量以查找可能的嫌疑犯。

相关问题