The Source for Java Technology Collaboration
User: Password:
Register | Login help    

Search

Online Books:
java.net on MarkMail:


Comparing objects that might be arrays

Posted by emcmanus on July 20, 2007 at 7:50 AM PDT

I was using this Java idiom today, not for the first time, and thought I'd blog it for people not aware of it. You probably know that if you compare two objects x and y using x.equals(y), the result will be false if they are distinct arrays, even if their contents are the same. There is an easy way to get the right result for arrays. It is
Arrays.deepEquals(new Object[] {x}, new Object[] {y}). This works if x and y are plain objects, or null, or primitive arrays, or reference arrays. The only case where you might like it to work but it doesn't is for collections containing arrays, for example Set<int[]>.

Of course the idiom is a bit clunky and it's worth considering whether a new method
Something.deepEquals(Object x, Object y) might not be a useful addition. But where might it go? Arrays?

Related Topics >> Programming      
Comments
Comments are listed in date ascending order (oldest first)