Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package examples;
  import java.util.Map;
  import org.mapdb.DB;
  import org.mapdb.DBMaker;
  import org.mapdb.Utils;
  *	Demonstrates HashMaps with non-standard types of objects as key or value.
 public class Custom_Value {

MapDB uses custom serialization which stores class metadata at single place. Thanks to it is 10x more efficient than standard Java serialization. Using custom values in MapDB has three conditions: 1) classes should be immutable. There is instance cache, background serialization etc Modifing your classes after they were inserted into MapDB may leed to unexpected things. 2) You should implement `Serializable` marker interface. MapDB tries to stay compatible with standard Java serialization. 3) Even your values should implement equalsTo method for CAS (compare-and-swap) operations.
     public static class Person implements Serializable{
         final String name;
         final String city;
         public Person(String nString c){
             this. = n;
             this. = c;
         public String getName() {
             return ;
         public String getCity() {
             return ;
         public boolean equals(Object o) {
             if (this == oreturn true;
             if (o == null || getClass() != o.getClass()) return false;
             Person person = (Persono;
             if ( != null ? !.equals( : != nullreturn false;
             if ( != null ? !.equals( : != nullreturn false;
             return true;
     public static void main(String[] args) {
         // Open db in temp directory
         File f = Utils.tempDbFile();
 		DB db = DBMaker.newFileDB(f)
 		// Open or create table
 		Map<String,PersondbMap = db.getTreeMap("personAndCity");
 		// Add data
 		Person bilbo = new Person("Bilbo","The Shire");
 		Person sauron = new Person("Sauron","Mordor");
 		Person radagast = new Person("Radagast","Crazy Farm");
 		// Commit and close
         // Second option for using cystom values is to use your own serializer.
         // This usually leads to better performance as MapDB does not have to
         // analyze the class structure.
         class CustomSerializer implements Serializer<Person>, Serializable{
             public void serialize(DataOutput outPerson valuethrows IOException {
            public Person deserialize(DataInput inint availablethrows IOException {
                return new Person(in.readUTF(), in.readUTF());
        Serializer<Personserializer = new CustomSerializer();
        DB db2 = DBMaker.newTempFileDB().make();
        Map<String,Personmap2 = db2.createHashMap("map"falsenullserializer); //key serializer is null (use default)
        map2.put("North"new Person("Yet another dwarf","Somewhere"));

New to GrepCode? Check out our FAQ X