2013-10-25 75 views
0

做工精细字符串,如果建立这样的:创建一个从字节[]

String ss = new String({1,2}); 

甚至这样:

String ss = new String({(byte)1,(byte)2}); 

什么是

byte [] d = {1,2}; 
String ss = new String(d); 

但是,如果建立这样的失败问题?

+2

编译器说什么? – Ingo

回答

3

String ss = new String(new byte[]{1,2});

String ss = new String({1,2});不起作用,因为数组不能简单地做一个{}块进行初始化。它需要前面的new someThing[]

+1

请注意,识别正在使用的编码是一种很好的做法,例如,新的字符串(新的字节[] {1,2},“UTF-8”) - 否则这个命令是平台特定的,使用平台的默认字符集 – rec

+0

@Rene嗯,这是正确的,它的工作原理。但问题是,为什么OP的代码失败。原因是语法不正确。你可能已经提到过。 – Fildor

0
String ss = new String (array of bytes); 
we can pass here array of bytes but in 
String ss = new String({1,2}); {1 , 2} this is not an array and 
String ss = new String({(byte)1,(byte)2}); {(byte)1,(byte)2} this is also not an array 

So we can simply use 
String ss = new String(new byte[]{1,2});