Java byte[] 数组的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22356792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:12:04  来源:igfitidea点击:

Length of byte[] array

javaarraysbyte

提问by

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];
}

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

b将存储数组的每个字节,但我似乎无法正确获取数组的长度。

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

采纳答案by Brian

Use bytes.lengthwithout the ()

使用bytes.length()

回答by Sabuj Hassan

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

它不是bytes.length(),它的bytes.length

回答by Maroun

See the JLS - 10.7. Array Members:

请参阅JLS - 10.7。数组成员

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.

数组类型的成员如下:

public final field length,其中包含所述阵列的部件的数量。长度可以是正数或零。

lengthis a property, not a method. You should write:

length是一个属性,而不是一个方法。你应该写:

bytes.length

回答by barak manos

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

要获取数组的长度,请使用length. 例如:

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

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

要获取字符串的长度,请使用length(). 例如:

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

回答by Sudz

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

getBytes() 使用平台的默认字符集将 String 编码为字节序列,并将结果存储到新的字节数组中。

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

尝试打印字节,您将看到与原始字符串相比长度可能不同的编码值。