加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 02:48:04 所属栏目:Java 来源:网络整理
导读:我希望两个相同字符串的字节表示也相同,但似乎并非如此.下面是我用来测试它的代码. String test1 = "125"; String test2 = test1; if(test1.equals(test2)) { System.out.println("These strings are the same"); } byte[] array1 = test1.getBytes(); byte[
我希望两个相同字符串的字节表示也相同,但似乎并非如此.下面是我用来测试它的代码.
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;

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读