byte arr[] = new byte[] {56, 99, 87, 77, 73, 90, 105, -23, -52, -85, -9, -55, -115, 11, -127, -127};
String s= new String(arr);
Arrays.equals(arr, s.getBytes())); // returns false
为什么数组不相等?
byte arr[] = new byte[] {56, 99, 87, 77, 73, 90, 105, -23, -52, -85, -9, -55, -115, 11, -127, -127};
String s= new String(arr);
Arrays.equals(arr, s.getBytes())); // returns false
为什么数组不相等?
这取决于你的Charset.defaultCharset()
分.这决定了字节的解释方式.负值可能是表示代码点的一种非规范方式.
(见这个伟大的答案:https://stackoverflow.com/a/7934397/461499)
然后,将getBytes()
重新解释为String
将成为标准方式,并返回true
System.out.println(Charset.defaultCharset()); //UTF-8 here :)
byte arr[] = new byte[] {56, 99, 87, 77, 73, 90, 105, -23, -52, -85, -9, -55, -115, 11, -127, -127};
String s= new String(arr);
System.out.println(s);
// [56, 99, 87, 77, 73, 90, 105, -17, -65, -67, -52, -85, -17, -65, -67, -55, -115, 11, -17, -65, -67, -17, -65, -67]
byte arr2[] = new byte[] {56, 99, 87, 77, 73, 90, 105, -17, -65, -67, -52, -85, -17, -65, -67, -55, -115, 11, -17, -65, -67, -17, -65, -67};
System.out.println(Arrays.toString(s.getBytes()));
System.out.println(Arrays.equals(arr, s.getBytes())); // returns false
String s2= new String(arr2);
System.out.println(Arrays.toString(s2.getBytes()));
System.out.println(Arrays.equals(arr2, s2.getBytes())); // returns true