Java 比较数组
我有两个未知类型的数组...有没有办法检查元素是否相同:
public static boolean equals(Object a , Object b) {
if (a instanceof int[])
return Arrays.equals((int[]) a, (int[])b);
if (a instanceof double[]){
////etc
}
我想在没有所有instanceof检查的情况下执行此操作...
I have two Arrays of unknown type...is there a way to check the elements are the same:
public static boolean equals(Object a , Object b) {
if (a instanceof int[])
return Arrays.equals((int[]) a, (int[])b);
if (a instanceof double[]){
////etc
}
I want to do this without all the instanceof checks....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
ArrayUtils.isEquals() 来自 Apache Commons 正是这样做的。它还处理多维数组。
ArrayUtils.isEquals() from Apache Commons does exactly that. It also handles multi-dimensional arrays.
您应该尝试 Arrays.deepEquals(a, b)
You should try
Arrays.deepEquals(a, b)
数组实用程序类可能对此有所帮助:
http://download. oracle.com/javase/1.4.2/docs/api/java/util/Arrays.html
有一个方法:
比较对象数组。
Arrays utilities class could be of help for this:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Arrays.html
There is a method:
That compares arrays of objects.
如果数组类型未知,则不能简单地转换为
Object[]
,因此无法使用equals
、deepEquals
中的方法代码>java.util.Arrays。但是,您可以使用反射来获取数组的长度和项目,并递归地比较它们(项目本身可能是数组)。
这是一个比较两个对象的通用实用方法(也支持数组),它允许一个甚至两个都为空:
If the array type is unknown, you cannot simply cast to
Object[]
, and therefore cannot use the methods (equals
,deepEquals
) injava.util.Arrays
.You can however use reflection to get the length and items of the arrays, and compare them recursively (the items may be arrays themselves).
Here's a general utility method to compare two objects (arrays are also supported), which allows one or even both to be null: