是什么 ArrayIndexOutOfBoundsException 我的意思是我该怎么摆脱它?下面是触发异常的代码示例:
ArrayIndexOutOfBoundsException
String[] names = { "tom", "bob", "harry" }; for (int i = 0; i <= names.length; i++) { System.out.println(names[i]); }
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]。例如:
name.length
name[2]
name.length - 1
for
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'); }
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和控制器的所有示例变量以查找可能的嫌疑犯。
17条答案
按热度按时间ioekq8ef16#
在代码中,您访问了从索引0到字符串数组长度的元素。
name.length
给出字符串对象数组中字符串对象的数目,即3,但最多只能访问索引2name[2]
,因为可以从索引0到name.length - 1
你去哪了name.length
对象数。即使在使用
for
循环以索引0开始,应该以name.length - 1
. 在数组a[n]中,可以从a[0]访问a[n-1]。例如:
就你而言:
iqih9akk17#
对于看似神秘的arrayindexoutofboundseceptions(即显然不是由您自己的数组处理代码引起的),我见过的最常见的情况是并发使用simpledateformat。特别是在servlet或控制器中:
如果两个线程同时输入simplatedateformat.parse()方法,您可能会看到arrayindexoutofboundsexception。注意simpledateformat类javadoc的同步部分。
确保在您的代码中没有以servlet或控制器等并发方式访问simpledateformat之类的线程不安全类的地方。检查servlet和控制器的所有示例变量以查找可能的嫌疑犯。