[英]contains method for list of array of bytes
so i have a list List<byte[]>
lets say "fullList", whereby some other piece of code generates another List containing some byte[]
partialList. 所以我有一个列表List<byte[]>
可以说“ fullList”,由此另一段代码生成另一个包含某些byte[]
partialList的List。 so i use the .contain method which always fails for searching got byte[] in partialList from the fullList. 因此,我使用.contain方法始终无法从fullList中搜索partialList中的goted字节[]。 Why is this?? 为什么是这样??
List<byte[]> fullList = {some byte[] arrays added here..}
List<byte[]> partialList = {some byte[] arrays added here..}
byte[] toCheck = partialList.get(0);
System.out.println("The check is "+ fullList.contains(tocheck));
The problem is that Java arrays do not implement equals
properly , ie two arrays are considered "equal" only if their memory address is the same, ie if they are the exact same object reference. 问题是Java数组不能正确实现equals
,即两个数组只有在其内存地址相同(即它们是完全相同的对象引用)时才被视为“相等”。
byte[] foo = {1,2,3};
byte[] bar = {1,2,3};
System.out.println(foo.equals(bar)); // prints 'false'
To work around this problem, you could either encode those byte[]
as numbers and use List<Integer>
(or Long
) instead, or implement your own contains method using Arrays.equals
要变通解决此问题,您可以将这些byte[]
编码为数字,然后使用List<Integer>
(或Long
),或者使用Arrays.equals
实现自己的contains方法。
boolean contains(List<byte[]> arrays, byte[] other) {
for (byte[] b : arrays)
if (Arrays.equals(b, other)) return true;
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.