Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2007

Tip: Looking for answers? Try searching our database.

Sorting Lists of byte arrays

Thread view: 
mikew01 - 11 Dec 2007 14:59 GMT
Hello, I need to compare 2 lists of byte arrays.
I wanted to use something like Collections.sort then compare each
array in the order they came out of the List but this will not work
because a byte array object does not implement Comparable, so I'm
doing this at present...

<code>
protected void compareDBVsIProds( List convertedProds, List
iProducts )
{
int matches = iProducts.size();

        for( int i = 0; i < iProducts.size(); i++ )
        {
            byte[] iArr = ( byte[] ) iProducts.get( ( i  ) );

            for( int j = 0; j < convertedProds.size(); j++ )
            {
                byte[] prodArr = ( byte[] )convertedProds.get( j );

                if( Arrays.equals( iArr, prodArr ) )
                {
                    matches--;
                    break;
                }
            }
        }

        if( matches != 0 )
        {
            String error =  matches + " products have not been matched";
            throw new RuntimeException( error );
        }
}
</code>

Could anyone suggest a neater way of achieving this task?

TIA

Mike.
Lasse Reichstein Nielsen - 11 Dec 2007 17:55 GMT
> Hello, I need to compare 2 lists of byte arrays.
> I wanted to use something like Collections.sort then compare each
> array in the order they came out of the List but this will not work
> because a byte array object does not implement Comparable, so I'm
> doing this at present...

Try:

Collections.sort(myListOfByteArrays, new Comparator<byte[]> {
   // compares byte arrays using lexical ordering
   public int compare(byte[] arr1, byte[] arr2) {
      int len = Math.min(arr1.length, arr2.length);
      for(int i = 0; i < len; i++) {
        int cmp = arr1[i] - arr2[i];
        if (cmp != 0) { return cmp; }
      }
      return arr1.length - arr2.length;
   }
 });

Warning: written directly in newsreader, not tested :)

When you have sorted the lists, you can run through them, using
a pair of iterators and see if they match, perhaps using the
same comparator again.

/L
Signature

Lasse Reichstein Nielsen  -  lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
 'Faith without judgement merely degrades the spirit divine.'

Eric Sosman - 11 Dec 2007 18:02 GMT
> Hello, I need to compare 2 lists of byte arrays.
> I wanted to use something like Collections.sort then compare each
[quoted text clipped - 33 lines]
>
> Could anyone suggest a neater way of achieving this task?

    It seems you don't care about the order of items in
the two Lists, but only about their presence: a,b is
to be considered "equal" to b,a.  (In fact, it seems
you want a,b,a to be "equal" to a,b.  Stranger still,
the code says that a,b is "equal" to a,b,c but that
a,b,c is "unequal" to a,b -- are you sure you've coded
what you actually intend?)

    That aside, you can certainly sort the Lists of
byte arrays.  There are two Collections.sort() methods:
one that uses the natural order of collections of
Comparable objects (which doesn't help you), but another
which uses a Comparator object that you can supply.
By sorting both Lists, you can turn the O(N*N) process
shown above into an O(N*log(N)) process; whether this
is or isn't worth while depends on the value of N and
of the messy details hidden behind the Big-O's.

    It seems attractive to use a Set (where order doesn't
matter) instead of a List (where it does), but that will
require wrapping each byte array in a class with a little
intelligence.  Still, that may not be a drawback: Just
how "raw" are these arrays supposed to be, anyhow?  If
they have some kind of significance, perhaps the wrapping
class will turn out to have other uses anyhow.

Signature

Eric.Sosman@sun.com

Daniel Pitts - 11 Dec 2007 18:41 GMT
> Hello, I need to compare 2 lists of byte arrays.
> I wanted to use something like Collections.sort then compare each
> array in the order they came out of the List but this will not work
> because a byte array object does not implement Comparable, so I'm
> doing this at present...
Use the Comparator method overloaded version of sort:

Collections.sort(byteArrays, new Comparator<byte[]>() {
   public int compare(byte[] o1, byte[] o2) {
    // do your byte comparison here.
   }
});
Signature

Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Roedy Green - 12 Dec 2007 00:51 GMT
On Tue, 11 Dec 2007 06:59:43 -0800 (PST), mikew01
<mikew01@blueyonder.co.uk> wrote, quoted or indirectly quoted someone
who said :

> this will not work
>because a byte array object does not implement Comparable,

You can use a Comparator with Arrays.sort

For sorting byte arrays, a Radixsort will be very quick. See
http://mindprod.com/jgloss/radixsort.html
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.