【问题】
android中想要去初始化byte数组,用如下代码:
//currentlongAddress = new byte[100]; //[109, -24, 19, -38, 28] currentlongAddress = new byte[100]{109, -24, 19, -38, 28};
结果出错:
Cannot define dimension expressions when an array initializer is provided |
如图:
【解决过程】
1.搜:
android initialize byte array
参考:
java – Initialize unsigned byte array using hex number – Stack Overflow
貌似我上面写法是对的,但是负数不能直接写,要转换为byte?
2.结果此时才看到,原来错误是:
Cannot define dimension expressions when an array initializer is provided
3.所以,去看看对应的定义,是:
private byte[] currentlongAddress;
参考:
Array error in java – Stack Overflow
把上面100去掉,变成:
currentlongAddress = new byte[]{109, -24, 19, -38, 28};
就可以了。
4.但是还是想要实现:
数组长度是100,但是只初始化前面几个数字。
改为:
currentlongAddress = new byte[100]; currentlongAddress = {109, -24, 19, -38, 28};
也不行,会出错:
Array constants can only be used in initializers |
5.貌似只能一个个赋值了???
参考:
Java Array 数组 – 不要依赖这里 因为你有大脑 – ITeye技术网站
也还是没用,貌似只能一点点赋值。
无奈的,最终只能用:
currentlongAddress = new byte[100]; //currentlongAddress = {109, -24, 19, -38, 28}; currentlongAddress[0] = 109; currentlongAddress[1] = -24; currentlongAddress[2] = 19; currentlongAddress[3] = -38; currentlongAddress[4] = 28;
才实现所需要的:
申请一个足够大的,100长度的数组;
然后给前面几个赋值。
【总结】
Java语言,再次证明了语法上,就做得很不好用。
其他的不好用,详见:
转载请注明:在路上 » 【已解决】Android(即Java)中字节数组初始化出错:Cannot define dimension expressions when an array initializer is provided