Java:相同的字符串返回不同的字节数组

前端之家收集整理的这篇文章主要介绍了Java:相同的字符串返回不同的字节数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望两个相同字符串的字节表示也相同,但似乎并非如此.下面是我用来测试它的代码.
String test1 = "125";
    String test2 = test1;

    if(test1.equals(test2))
    {
        System.out.println("These strings are the same");
    }

    byte[] array1 = test1.getBytes();
    byte[] array2 = test2.getBytes();

    if(array1.equals(array2))
    {
        System.out.println("These bytes are the same");
    }
    else
    {
        System.out.println("Bytes are not the same:\n" + array1 + " " + array2);
    }

在此先感谢您的帮助!

解决方法

两个相同但不相关的String对象的字节表示肯定是逐字节相同的.但是,只要String对象不相关,它们就不会是同一个数组对象.

您的代码错误地检查数组相等性.以下是如何解决它:

if(Arrays.equals(array1,array2)) ...

此外,即使您多次在同一个String对象上调用getBytes,您也​​会获得不同的字节数组:

String test = "test";
byte[] a = test.getBytes();
byte[] b = test.getBytes();
if (a == b) {
    System.out.println("same");
} else {
    System.out.println("different");
}

The above code prints "different".

这是因为String不会保留getBytes的结果.

注意:您的代码会在相同的对象上调用两次getBytes,因为这一行

String test2 = test1;

不复制字符串,但创建对同一字符串对象的第二个引用.

原文链接:https://www.f2er.com/java/127838.html

猜你在找的Java相关文章