Search code examples
javamapdb

How to use byte array as a key in MapDB's implementation of BTreeMap


Is there any way to use byte array as a key in BTreeMap like this:

BTreeMap<byte[], Integer> myBTreeMap = db.getTreeMap("myBTreeMap");

Currently this exception is thrown when trying to put new object into the map:

Exception in thread "main" java.lang.ClassCastException: [B cannot be cast to java.lang.Comparable ...

What is proper way of making this to work? I would like to know solution without using wrapper classes.

Any ideas are welcome.

[UPDATE]

I've used proposed solution by SJuan76:

    BTreeMap<byte[], Integer> myBTreeMap = db.createTreeMap("myBTreeMap")
            .comparator(SignedBytes.lexicographicalComparator())
            .makeOrGet();

Used comparator can be found in Guava library if needed.


Solution

  • Looking at the Javadoc (I guess it is the Javadoc for that project and not another one, it would have been nice of you to link to it) there is defined a constructor that takes a Comparator<K>. Use that constructor and pass it a Comparator<byte[]> that gives the ordering you desire.