Length of byte[] array

徘徊边缘 提交于 2019-12-08 15:53:39

问题


String str = "123456789";
byte[] bytes = str.getBytes();

I want to make the following loop

for (int j = 0; j < bytes.length(); j++) {
  b = bytes[j];
}

b will store each byte of my array, but I can't seem to get the length of the array correctly.

Error:cannot find symbol
Problem solved:  bytes.length instead of  bytes.length()

回答1:


Use bytes.length without the ()




回答2:


See the JLS - 10.7. Array Members:

The members of an array type are all of the following:

The public final field length, which contains the number of components of the array. length may be positive or zero.

length is a property, not a method. You should write:

bytes.length



回答3:


Its not bytes.length(), its bytes.length




回答4:


In order to get the length of an array, use length. For example:

int[] arr = {1,2,3};
int length = arr.length;

In order to get the length of a string, use length(). For example:

String str = "123";
int length = str.length();



回答5:


getBytes() Encodes the String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

Try to print the bytes you will see the encoded values which may differ in length compare to original string.



来源:https://stackoverflow.com/questions/22356792/length-of-byte-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!