Databoard Snippets
Introduction
This document contains a some Java coding snippets for the Databoard library.
Object Deep-Copy
The binding class can be used for cloning objects. All copied objects are deep. Mutable objects are duplicated, and immutable are referenced.
// Binding can copy objects. All copies are deep.
// Mutable objects are duplicated, immutable are referenced.
// For instance, in object array, the array is copied, but its
// immutable literal instances (e.g. 1) is referenced.
Object[] original = new Object[] { 1, "X", 123.456 };
Binding binding = Bindings.getBinding( original.getClass() );
Object[] copy = (Object[]) binding.cloneUnchecked( original );
// Print the objects
System.out.println( "Original: "+binding.toString( original ) );
System.out.println( "Clone : "+binding.toString( copy ) );
Recursive classes can also be cloned, but they must be annotated with @Referable
tag.
static @Referable class X {
public X reference;
}
public static void main(String[] args) throws BindingConstructionException, BindingException {
// Create recursive instance
X original = new X();
original.reference = original;
Binding binding = Bindings.getBinding( original.getClass() );
X copy = (X) binding.cloneUnchecked( original );
// Print the objects
System.out.println( "Original: "+binding.toString( original ) );
System.out.println( "Clone : "+binding.toString( copy ) );
}
Object Deep-Compare
Binding can compare any two instances. The compare function is deep.
Binding binding = Bindings.getBindingUnchecked( int[].class );
int[] array1 = new int[] { 1, 2, 3 };
int[] array2 = new int[] { 1, 2, 3 };
int[] array3 = new int[] { 2, 3, 4 };
if ( binding.compare(array1, array2) == 0 ) {
System.out.println( "array1 is equal to array2" );
} else {
System.out.println( "array1 is not equal to array2" );
}
if ( binding.compare(array1, array3) == 0 ) {
System.out.println( "array1 is equal to array3" );
} else {
System.out.println( "array1 is not equal to array3" );
}
Two bindings can compare instances of same datatype, even if they are of different classes.
ArrayList<Integer> array4 = new ArrayList<Integer>();
Binding binding2 = Bindings.getBindingUnchecked( ArrayList.class, Integer.class );
array4.add( 1 );
array4.add( 2 );
array4.add( 3 );
if ( Bindings.compare(binding, array1, binding2, array4) == 0 ) {
System.out.println( "array1 is equal to array4" );
} else {
System.out.println( "array1 is not equal to array4" );
}
Object deep-hashcode
Binding can calculate deep hashcode for any instance
Binding binding = Bindings.getBindingUnchecked( int[].class );
int[] array1 = new int[] { 1, 2, 3 };
int[] array2 = new int[] { 1, 2, 3 };
int[] array3 = new int[] { 2, 3, 4 };
System.out.println( "Hashcode for array1 is " + binding.hashValue( array1 ) );
System.out.println( "Hashcode for array2 is " + binding.hashValue( array2 ) );
System.out.println( "Hashcode for array3 is " + binding.hashValue( array3 ) );