数组索引超出范围的异常Java [英] Array index out of bound exception java

查看:122
本文介绍了数组索引超出范围的异常Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将数组索引抛出绑定异常.我已初始化1000的大小,但尚未充分利用.未使用的索引的确切值是什么?

The following code throws array index out of bound exception. I have initialized a size of 1000 yet not fully utilized. What exactly are the values of unused indices?

byte[] buffer=new byte[1000];
     String s="i am a stupid";
     buffer=s.getBytes();

     System.out.println(buffer[30]);

推荐答案

当您调用 String#getBytes 方法时,您将获得一个新数组,该数组的长度等于代表字符串.由于 Java文档:

When you call the String#getBytesmethod you get a new array, initialized with the length equals to the number of bytes needed to represent the string. Due to Java docs:

使用给定的字符集将此字符串编码为字节序列,并将结果存储到新的字节数组中.

Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.

在您的情况下,它的长度等于字符串的长度(13个字节),总之小于30.这就是您尝试获取第30个元素时得到此异常的原因.

In your case it's length equals to length the string (13 bytes) and it's less then 30 anyway. That is the reason you get this exception, while trying to get the 30th element.

如果需要使用从字符串变成数组的数组来初始化缓冲区变量,则需要使用

If you need to initialize your buffer variable with an array you become from string, you need to use System#arraycopy method:

byte[] byteAr = s.getBytes();
System.arraycopy(byteAr, 0, buffer, 0, byteAr.length);

如果您想知道,默认情况下用于初始化数组的值是什么,因此这是数组所包​​含的数据类型的默认途径.如果是字节,则默认值为0.

If you wish to know, what are values used to initialize an array by default, so it's a default velues for datatype your array consist of. In case of bytes, the default value is 0.

这篇关于数组索引超出范围的异常Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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