简体   繁体   中英

Why am i getting ArrayIndexOutOfBoundsException

ArrayList<String> al = new ArrayList(Arrays.asList(Answers));
Collections.shuffle(al);
char answer=(char) (al.indexOf(right)+65);
for(int i=0;i<al.size();i++){
    al.set(i, ((char)(i+65))+")"+al.get(i));
}
String[] s=al.toArray(new String[al.size()]);
int n = s.length+1;
String[] ret = new String[n];
System.arraycopy(s,0,ret,1,n);
ret[0]=answer+"";
return ret;

I expected it to work and not crash but i am getting this instead:"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException" on this line:

System.arraycopy(s,0,ret,1,n);

I don't know why and any help is welcome.

I think you wanted

System.arraycopy(s, 0, ret, 1, s.length);

Currently, you're trying to copy n (which equals s.length + 1 ) elements out of s .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM