問題描述
我有一個字節數組,里面有一個~已知的二進制序列.我需要確認二進制序列是它應該是什么.除了 ==
之外,我還嘗試了 .equals
,但都沒有成功.
I have a byte array with a ~known binary sequence in it. I need to confirm that the binary sequence is what it's supposed to be. I have tried .equals
in addition to ==
, but neither worked.
byte[] array = new BigInteger("1111000011110001", 2).toByteArray();
if (new BigInteger("1111000011110001", 2).toByteArray() == array){
System.out.println("the same");
} else {
System.out.println("different'");
}
推薦答案
在你的例子中,你有:
if (new BigInteger("1111000011110001", 2).toByteArray() == array)
在處理對象時,java中的==
會比較引用值.您正在檢查 toByteArray()
返回的對數組的引用是否與 array
中保存的引用相同,這當然不可能是真的.此外,數組類不會覆蓋 .equals()
因此其行為是 Object.equals()
的行為,它也只比較參考值.
When dealing with objects, ==
in java compares reference values. You're checking to see if the reference to the array returned by toByteArray()
is the same as the reference held in array
, which of course can never be true. In addition, array classes don't override .equals()
so the behavior is that of Object.equals()
which also only compares the reference values.
為了比較兩個數組的內容,數組類
byte[] array = new BigInteger("1111000011110001", 2).toByteArray();
byte[] secondArray = new BigInteger("1111000011110001", 2).toByteArray();
if (Arrays.equals(array, secondArray))
{
System.out.println("Yup, they're the same!");
}
這篇關于比較兩個字節數組?(爪哇)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!