<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-5010874239602565935</id><updated>2011-10-27T12:07:36.963+01:00</updated><category term='overriding equals'/><category term='Processing randomSeed'/><category term='Java'/><category term='Processing NetBeans copy paste'/><category term='overriding equals java'/><category term='overloading'/><title type='text'>Light on Java</title><subtitle type='html'>Graphics, Processing, Sorting, Systems and suchlike.
Martin Humby's Java blog</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>18</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-2949144643193449659</id><published>2011-10-27T12:07:00.000+01:00</published><updated>2011-10-27T12:07:36.974+01:00</updated><title type='text'>Simpler inheritance diagrams</title><content type='html'>&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-RSb83BKl0lA/Tqk6NVzTKFI/AAAAAAAAAHE/P3rMGVge_rk/s1600/Equals+Fig+2.bmp" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;br /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-lgNgDtRl838/Tqk6NwzUnqI/AAAAAAAAAHM/1ZuhN30FAD8/s1600/Equals+Fig+1.bmp" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/-lgNgDtRl838/Tqk6NwzUnqI/AAAAAAAAAHM/1ZuhN30FAD8/s1600/Equals+Fig+1.bmp" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Two equality groups&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-RSb83BKl0lA/Tqk6NVzTKFI/AAAAAAAAAHE/P3rMGVge_rk/s1600/Equals+Fig+2.bmp" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://4.bp.blogspot.com/-RSb83BKl0lA/Tqk6NVzTKFI/AAAAAAAAAHE/P3rMGVge_rk/s1600/Equals+Fig+2.bmp" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Partial separation&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-2949144643193449659?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/2949144643193449659/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2011/10/simpler-inheritance-diagrams.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/2949144643193449659'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/2949144643193449659'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2011/10/simpler-inheritance-diagrams.html' title='Simpler inheritance diagrams'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/-lgNgDtRl838/Tqk6NwzUnqI/AAAAAAAAAHM/1ZuhN30FAD8/s72-c/Equals+Fig+1.bmp' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-6703570068198508920</id><published>2011-05-26T12:30:00.000+01:00</published><updated>2011-05-26T12:30:43.462+01:00</updated><title type='text'>Turkish Cat Selçuk</title><content type='html'>&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-m6srTSGIXE4/Td45j8iL5SI/AAAAAAAAAG8/UX8_hXNlc7A/s1600/Turkish%2BCat.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="400" src="http://3.bp.blogspot.com/-m6srTSGIXE4/Td45j8iL5SI/AAAAAAAAAG8/UX8_hXNlc7A/s400/Turkish%2BCat.PNG" width="300" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-6703570068198508920?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/6703570068198508920/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2011/05/turkish-cat-selcuk.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/6703570068198508920'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/6703570068198508920'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2011/05/turkish-cat-selcuk.html' title='Turkish Cat Selçuk'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/-m6srTSGIXE4/Td45j8iL5SI/AAAAAAAAAG8/UX8_hXNlc7A/s72-c/Turkish%2BCat.PNG' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-2252973786659313177</id><published>2009-12-19T16:15:00.034Z</published><updated>2010-01-31T01:31:25.644Z</updated><title type='text'>How to code multiple dispatch in standard Java</title><content type='html'>This posting continues the theme of multiple dispatch related to the binary method problem and shows a basic double dispatch implementation in standard Java. An appropriate method for computing whether two Shape objects overlap is selected based on runtime argument type. More Shape classes can be added without modifying existing code for shapes (rectangle, square, circle, ect.) already written. Doing it with a drop-through &lt;span style="font-family: courier;"&gt;instanceof&lt;/span&gt; list is contrasted with low-overhead selection by argument type from an array of methods.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: 130%; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Multiple and predicate dispatching&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Single, dynamic dispatching is used by OOP languages to call a designated method based on the runtime type of an object currently at a reference. When the language also features static (compile time) type checking the object's actual type will generally be either the nominal type of the reference or a subclass of that type. In either case, if the object does not have a method matching the static signature of the called method a compile time or runtime error results. For applications written using so called managed-code an exception is thrown at runtime. Using native code languages that do not provide this level of implicit type checking during execution, the error may vary from the method operating on spurious data to uncontrolled execution and possible program termination by the operating system.&lt;br /&gt;&lt;br /&gt;In a language that features static type checking and whatever the actual mechanism involved, we can model single dispatching by giving all objects a reference to a table of methods for their class. The compiler stores the table offset of any particular method and when a call against a reference nominally to an object of  a particular class is encountered, code is generated to retrieve the entry point for the method from the table. In the model a base class and each subclass has its own table - perhaps not the case as implemented. Overriding a method in a subclass the base-class method is replaced by the subclass method in the subclass' table. If a nominal superclass reference cites a subclass object at runtime, the subclass overridden method entry point is got from the table and this method is executed.&lt;br /&gt;&lt;br /&gt;Multiple dispatch extends this method selection mechanism to include the runtime type of method arguments.  Extending the model: single dispatching in a statically type-checked environment requires a single method selection table with one dimension. Without static checking an additional dimension is needed related to runtime type.  Multiple dispatch requires a table with as many additional dimensions as there are arguments significant to the selection process. The table can be implemented as one per class or one per base class and there can be a table for each multi-method or a single combined table with other tables referenced by its elements.&lt;br /&gt;&lt;br /&gt;To prove the concept we will look at implementing a single-method table for a method with a single significant argument in addition to object type. This implementation can be extended to include additional multi-methods by introducing additional tables.&lt;br /&gt;&lt;br /&gt;Predicate dispatch extends the multiple dispatch concept by allowing the runtime values of arguments and logical relationships between types and/or values to be significant for method selection. In OOP languages the multiple dispatch and predicate concepts are quite blurred. A reference can cite an object of its nominal class or a subtype and the value of a reference is the object it refers to, one value of which is its type. Ability to include logical selection statements that deal with type and/or other values appears to be the distinguishing factor.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: 130%; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Implementing multiple dispatch&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;There are a number of possibilities. To do multiple dispatch according to the book we are going to have to use the java.lang.reflect package. If you haven't tried any of this stuff already to get an idea of what it entails  you can Google 'Java Reflection' and have a look at some of Sun's postings.&lt;br /&gt;&lt;br /&gt;For a more low level view Dennis Sosnoski's articles on &lt;a href="http://www.ibm.com/developerworks/java/library/j-dyn0429/index.html"&gt;IBM developerWorks&lt;/a&gt; go down into the world of bytecode and beyond, up to replacing reflection with runtime code generation.&lt;br /&gt;&lt;br /&gt;As Dennis shows, using standard reflection is slow, very slow. Reflection may have a use for class initialization but what we are going to look at here is somthing far simpler and more akin to a native code approach - a DIY method table. A great advantage of implementing the table in Java is that it is pretty well guaranteed to be robust but there a number of difficulties to be overcome - methods not being a first-class data type for one.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: 130%; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;The binary method problem&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;A binary method is a method that operates on two or more objects of the same type. It has at least two arguments, perhaps one implicit - the reference to the current instance, the other the same type or to a related class. Suppose we write a base class with a binary method, how can we allow for this method being overridden in a way that works for instances of any subclass including those that have not yet been written and without changing code in the base class?&lt;br /&gt;&lt;br /&gt;Using instanceof and typecasting is one way, discussed briefly later,  but what is needed is something more akin to overriding methods but related to argument types as well as the instance type. So, how can you override a method substituting covariant arguments that can be used straight off with no typecasts? Without too much difficulty it turns out.&lt;br /&gt;&lt;br /&gt;In their paper presenting &lt;a href="http://www.cs.ucla.edu/%7Etodd/research/oopsla00.pdf"&gt;MultiJava&lt;/a&gt;, a Java extension supporting open classes and multiple dispatch, the authors cite the example of a Shape class with subclasses Rectangle, Circle etc. Shape has a binary method &lt;span style="font-family: courier;"&gt;intersect(Shape)&lt;/span&gt; that returns true if two shapes overlap. I am going to nick this example in a slightly modified form to show how we can implement multiple dispatch in bog standard code. The methodology is kept simple and easy to explain. Perhaps a more generalized solution could be posted later but currently it is worth noting that open classes and multiple dispatch are strongly related to not implementing the Visitor design pattern, enough said!&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: 130%; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Using double dispatch&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;First let's firm up what we are trying to achieve. In Shape nothing is known about rules for checking subclass intersection but in the first subclass, Rectangle say, we can write a method intersect(Rectangle).&lt;br /&gt;&lt;br /&gt;Using single dispatching we would override intersect(Shape) from the base class:&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt;"&gt;&amp;nbsp;   @Override public boolean intersect(Shape argument) {&lt;br /&gt;        if (argument instanceof Rectangle)&lt;br /&gt;            return intersect((Rectangle)argument);&lt;br /&gt;        return argument.intersect(this);&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;In fact this is programmed double dispatching. If the current class does not have a method to compute intersection with the actual type of the argument, &lt;span style="font-family: courier;"&gt;argument.intersect(this)&lt;/span&gt; is called to get the result: the method called depends on the argument type. Under this scheme each new subclass includes methods to compute intersection with an instance of itself and all the types that have already been written.&lt;br /&gt;&lt;br /&gt;This approach is fine: new shapes can be added as required without recoding any existing shapes and there is no problem with the kind of objections often made to using &lt;span style="font-size: 100%;"&gt;&lt;span style="font-family: courier;"&gt;instanceof&lt;/span&gt;&lt;/span&gt; selection. The only drawback is that if a class does not implement a method to handle intersection for all the other classes written to date, after an instance of one of those other classes calls its &lt;span style="font-size: 100%;"&gt;&lt;span style="font-family: courier new;"&gt;intersect()&lt;/span&gt;&lt;/span&gt; the subsequent call to &lt;span style="font-family: courier new;"&gt;argument.intersect(this)&lt;/span&gt; gets unterminated recursion and stack overflow. An unavoidable fact of life, but things do not look quite so good when we get up to ten or twelve shapes:&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt;"&gt;&amp;nbsp;   @Override public boolean intersect(Shape argument) {&lt;br /&gt;        if (argument instanceof Rectangle)&lt;br /&gt;            return intersect((Rectangle)argument);&lt;br /&gt;        if (argument instanceof Square)&lt;br /&gt;            return intersect((Square)argument);&lt;br /&gt;        if (argument instanceof Circle)&lt;br /&gt;            return intersect((Circle)argument);&lt;br /&gt;        if (argument instanceof Triangle)&lt;br /&gt;            return intersect((Triangle)argument);&lt;br /&gt;&lt;br /&gt;        //..........................&lt;br /&gt;&lt;br /&gt;        return argument.intersect(this);&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;If this sort of thing is considered an '&lt;a href="http://www.objectmentor.com/resources/articles/lsp.pdf"&gt;anathema to Object Oriented Design&lt;/a&gt;' for unary methods why should it be OK for binary methods?&lt;br /&gt;&lt;br /&gt;Apart from the call to &lt;span style="font-family: courier;"&gt;argument.intersect(this)&lt;/span&gt; there is really no element of multiple dispatching in the &lt;span style="font-family: courier new;"&gt;intersect(Shape)&lt;/span&gt; method. Case selection using &lt;span style="font-family: courier;"&gt;instanceof&lt;/span&gt; or even a more efficient isA construct [&lt;a href="http://martinsjava.blogspot.com/2009/11/overriding-equalsobject-optimally.html#isa"&gt;here&lt;/a&gt;] does not qualify. Multiple dispatching supplies immediate direction of execution to an appropriate method based on argument type. What is needed is a way of calling the required &lt;span style="font-family: courier new;"&gt;intersect(type)&lt;/span&gt; method directly.&lt;br /&gt;&lt;br /&gt;Initially we need to map type to the required offset in a table of methods and the least complicated way of doing it is to provide each class with an a property &lt;span style="font-family: courier new;"&gt;mtOffset()&lt;/span&gt; : method table offset - the offset of references to methods with an argument of that class' type in one or more method tables.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: 130%; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;The Shape base class&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Let's see how this works out in the abstract base class Shape:&lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;public abstract class Shape {&lt;br /&gt;&lt;br /&gt;    public static final int MAX_SHAPES = 10;&lt;br /&gt;&lt;br /&gt;    protected static int classMTOffset;&lt;br /&gt;&lt;br /&gt;    protected static int getOffset() {&lt;br /&gt;        return classMTOffset++;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    protected abstract int mtOffset();&lt;br /&gt;&lt;/pre&gt;For simplicity the maximum number of shape classes that can be written is the constant &lt;span style="font-family: courier;"&gt;MAX_SHAPES&lt;/span&gt;. It looks probable that the only way to make the size of the multi-method table fit runtime requirements exactly is to give it a nominal initial size and then expand it if required. For the moment we skip this complication. The method &lt;span style="font-family: courier new;"&gt;getOffset()&lt;/span&gt; is called by each subclass in turn when the class is initialized. &lt;span style="font-family: courier new;"&gt;getOffset()&lt;/span&gt; returns the value of the &lt;span style="font-family: courier new;"&gt;classMTOffset&lt;/span&gt; variable which is also incremented. Subclasses then implement the abstract &lt;span style="font-family: courier new;"&gt;mtOffset()&lt;/span&gt; method to return the value got during initialization.&lt;br /&gt;&lt;br /&gt;Now we come to the base type for &lt;span style="font-family: courier;"&gt;intersect()&lt;/span&gt; methods:&lt;br /&gt;&lt;pre class="brush: java; first-line: 22"&gt;&amp;nbsp;   protected static abstract class Intersect&lt;br /&gt;                                &amp;lt;T extends Shape, S  extends Shape&amp;gt; {&lt;br /&gt;&lt;br /&gt;        abstract boolean intersect(T a, S b) ;&lt;br /&gt;&lt;br /&gt;     // abstract boolean contains(T a, S b, int tolerance); // possibly&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;No first-class method type in Java so methods are implemented in nested classes. I am going to call these types Method Classes. There are pros and cons. A big pro is that any number of methods can be defined in a single class. An &lt;span style="font-family: courier;"&gt;intersect(Shape)&lt;/span&gt; multimethod only requires a single sub-method but we could include a method &lt;span style="font-family: courier;"&gt;contains(T, S)&lt;/span&gt; returning true if  the S type shape fits entirely within T type shape for example, or similar overloaded methods with additional arguments, a tolerance factor maybe.&lt;br /&gt;&lt;br /&gt;The characteristic shared by all &lt;span style="font-family: courier;"&gt;intersect(T a, S b)&lt;/span&gt; methods as overridden in &lt;span style="font-family: courier new;"&gt;Intersect &lt;/span&gt;subclasses is that they all have two arguments that are covariant with Shape. Argument type is constrained by the declaration of the generic parameters to be a Shape or a subclass. Constraint is optional but shows the intention. &lt;span style="font-family: courier new;"&gt;IntersectRectangle&lt;/span&gt; for example is declared as:&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt;"&gt;&amp;nbsp;    protected static class IntersectRectangle&lt;br /&gt;                            extends Intersect&amp;lt;Rectangle, Rectangle&amp;gt; {&lt;br /&gt;&lt;br /&gt;         @Override public boolean intersect(Rectangle t, Rectangle r) {&lt;br /&gt;             //..............&lt;br /&gt;         }&lt;br /&gt;     }&lt;br /&gt;&lt;/pre&gt;The important factor is that declaring &lt;span style="font-family: courier;"&gt;Intersect&lt;/span&gt; as a generic class allows &lt;span style="font-family: courier new;"&gt;intersect(T, S)&lt;/span&gt; to be overridden in this way. If for example, we write&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt;"&gt;&amp;nbsp;   Intersect ref = new IntersectRectangle();&lt;br /&gt;    Boolean b = ref.intersect(t, s);&lt;br /&gt;&lt;/pre&gt;the method called is &lt;span style="font-family: courier;"&gt;intersect(Rectangle t, Rectangle r)&lt;/span&gt;. Not a typecast in sight but the danger is that any subclass instance can be passed as an argument and passing the wrong kind gets a runtime error. We can design around this problem but a con is that this for the enclosing-class object must be passed as an argument. Of course it gets passed anyway. The dot before a method call can be seen as passing the reference that precedes it.&lt;br /&gt;&lt;br /&gt;In this implementation method classes are static nested classes rather than inner classes. Inner classes would be nice: the method body has implicit access to outer-class fields but, because every instance of an inner class carries a reference to the outer-class instance that created it, every outer-class object would need its own method table. Even worse, the execution cost of creating this table is added to the construction cost for every instance. Here a single table is used located in Shape:&lt;br /&gt;&lt;pre class="brush: java; first-line: 29"&gt;&amp;nbsp;&lt;br /&gt;&amp;nbsp;   protected static Intersect[][] intersectTable =&lt;br /&gt;                                     new Intersect[MAX_SHAPES][];&lt;br /&gt;&amp;nbsp;&lt;br /&gt;&lt;/pre&gt;The table has two dimensions one for each argument type. If a method has more arguments subject to multiple dispatch the table is implemented with that number of dimensions. The array of method classes for each class is added to the table when the class is initialized. The index of a method-class array depends on the value of &lt;span style="font-family: courier new;"&gt;mtOffset()&lt;/span&gt; for the class, which results from class initialization order and is arbitrary.&lt;br /&gt;&lt;br /&gt;The method-class array for all classes is the same size irrespective of how many Intersect descendants the class implements. If a method to suite a particular combination of arguments is not present the corresponding element will be null, a characteristic used implementing the &lt;span style="font-family: courier new;"&gt;intersect(Shape)&lt;/span&gt; method:&lt;br /&gt;&lt;pre class="brush: java; first-line: 33"&gt;&amp;nbsp;   public boolean intersect(Shape s) {&lt;br /&gt;        if (this == s) return true;&lt;br /&gt;&lt;br /&gt;        // get method table offsets for the two types&lt;br /&gt;        int thisMTO = this.mtOffset();&lt;br /&gt;        int sMTO = s.mtOffset();&lt;br /&gt;&lt;br /&gt;        // thisMTO indexes the table for the current class of object&lt;br /&gt;        // sMTO the offset for a method to process the argument's type&lt;br /&gt;        if (intersectTable[thisMTO][sMTO] != null) {&lt;br /&gt;&lt;br /&gt;            // this object has a method so call it&lt;br /&gt;            return intersectTable[thisMTO][sMTO].intersect(this, s);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // otherwise call the argument's method&lt;br /&gt;        return intersectTable[sMTO][thisMTO].intersect(s, this);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}  // end of Shape&lt;br /&gt;&lt;/pre&gt;There is no possibility that the wrong method is called - it is selected programmatically rather than by some scatterbrained programmer ;).&lt;br /&gt;&lt;br /&gt;The same strategy shown for &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; method selection is used to allow additional subclasses to be written: if a null element is found in the current instance's table it does not have a method. It is assumed that the argument implements a suitable method but if it does not a null pointer exception will be thrown rather than stack overflow: still an error but a more traceable result.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: 130%; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Implementing a Rectangle class&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: courier;"&gt;MT_OFFSET&lt;/span&gt; is initialized by calling &lt;span style="font-family: courier;"&gt;Shape.getOffset()&lt;/span&gt; and this class' entry in the multy-method table is done by &lt;span style="font-family: courier;"&gt;Rectangle.initMT()&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;public class Rectangle extends Shape {&lt;br /&gt;    public static final int MT_OFFSET = getOffset();&lt;br /&gt;    public static final boolean CLASS_INITIALIZED = initMT();&lt;br /&gt;&lt;br /&gt;    private static boolean initMT() {&lt;br /&gt;        intersectTable[MT_OFFSET] = new Intersect[MAX_SHAPES];&lt;br /&gt;        intersectTable[MT_OFFSET][MT_OFFSET] = new IntersectRectangle();&lt;br /&gt;        return true;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override protected int mtOffset() {&lt;br /&gt;        return MT_OFFSET;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public final int top, left, width, height, right, bottom;&lt;br /&gt;&lt;br /&gt;    public Rectangle(int left, int top, int width, int height) {&lt;br /&gt;        this.left = left;&lt;br /&gt;        this.top = top;&lt;br /&gt;        this.width = width;&lt;br /&gt;        this.height = height;&lt;br /&gt;        right = left + width;&lt;br /&gt;        bottom = top + height;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static class IntersectRectangle&lt;br /&gt;            extends Intersect&amp;lt;Rectangle, Rectangle&amp;gt; {&lt;br /&gt;&lt;br /&gt;        @Override public boolean intersect(Rectangle t, Rectangle r) {&lt;br /&gt;&lt;br /&gt;            return (t.right &amp;gt; r.left &amp;amp;&amp;amp; t.left &amp;lt; r.right &amp;amp;&amp;amp;&lt;br /&gt;                    t.bottom &amp;gt; r.top &amp;amp;&amp;amp; t.top &amp;lt; r.bottom);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override public String toString() {&lt;br /&gt;&lt;br /&gt;        return left + ", " + top + ", " + width + ", " + height;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;A new vector of sub-method references is created at the &lt;span style="font-family: courier;"&gt;MT_OFFSET&lt;/span&gt; for this class. The class only declares a single sub-method of the &lt;span style="font-family: courier;"&gt;intersect(Shape, Shape)&lt;/span&gt; multi-method leaving other entries in the vector blank. The implemented method is selected by the inherited &lt;span style="font-family: courier;"&gt;intersect(Shape)&lt;/span&gt; method when this is a Rectangle and its argument is also a Rectangle.   &lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Implementing other shapes&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Each new Shape implements sub-methods of &lt;span style="font-family: courier;"&gt;intersect(Shape, Shape)&lt;/span&gt; to compare instances of the class with the instances of that class and other shapes implemented to date. Square declares two sub-methods: &lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;public class Square extends Shape {&lt;br /&gt;&lt;br /&gt;    public static final int MT_OFFSET = getOffset();&lt;br /&gt;    public static final boolean CLASS_INITIALIZED = initMT();&lt;br /&gt;&lt;br /&gt;    static boolean initMT() {&lt;br /&gt;        intersectTable[MT_OFFSET] = new Intersect[MAX_SHAPES];&lt;br /&gt;        intersectTable[MT_OFFSET][Rectangle.MT_OFFSET] =&lt;br /&gt;            new IntersectRectangle();&lt;br /&gt;        intersectTable[MT_OFFSET][MT_OFFSET] =&lt;br /&gt;            new IntersectSquare();&lt;br /&gt;        return true;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override protected int mtOffset() {&lt;br /&gt;        return MT_OFFSET;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public final int top, left, side, right, bottom;&lt;br /&gt;&lt;br /&gt;    public Square(int left, int top, int side) {&lt;br /&gt;        this.left = left;&lt;br /&gt;        this.top = top;&lt;br /&gt;        this.side = side;&lt;br /&gt;        right = left + side;&lt;br /&gt;        bottom = top + side;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    static class IntersectSquare extends Intersect&amp;lt;Square, Square&amp;gt; {&lt;br /&gt;&lt;br /&gt;        @Override public boolean intersect(Square t, Square s) {&lt;br /&gt;            return (t.right &amp;gt; s.left &amp;amp;&amp;amp; t.left &amp;lt; s.right &amp;amp;&amp;amp;&lt;br /&gt;                    t.bottom &amp;gt; s.top &amp;amp;&amp;amp; t.top &amp;lt; s.bottom);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    static class IntersectRectangle extends Intersect&amp;lt;Square, Rectangle&amp;gt; {&lt;br /&gt;&lt;br /&gt;        @Override public boolean intersect(Square t, Rectangle r) {&lt;br /&gt;            return (t.right &amp;gt; r.left &amp;amp;&amp;amp; t.left &amp;lt; r.right &amp;amp;&amp;amp;&lt;br /&gt;                    t.bottom &amp;gt; r.top &amp;amp;&amp;amp; t.top &amp;lt; r.bottom);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override public String toString() {&lt;br /&gt;&lt;br /&gt;        return left + ", " + top + ", " + side;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Circle has three intersect() sub-methods: &lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;public class Circle extends Shape {&lt;br /&gt;&lt;br /&gt;    public static final int MT_OFFSET = getOffset();&lt;br /&gt;    public static final boolean CLASS_INITIALIZED = initMT();&lt;br /&gt;&lt;br /&gt;    static boolean initMT() {&lt;br /&gt;        intersectTable[MT_OFFSET] = new Intersect[MAX_SHAPES];&lt;br /&gt;        intersectTable[MT_OFFSET][Rectangle.MT_OFFSET] =&lt;br /&gt;            new IntersectRectangle();&lt;br /&gt;        intersectTable[MT_OFFSET][Square.MT_OFFSET] =&lt;br /&gt;            new IntersectSquare();&lt;br /&gt;        intersectTable[MT_OFFSET][MT_OFFSET] = new IntersectCircle();&lt;br /&gt;        return true;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override protected int mtOffset() {&lt;br /&gt;        return MT_OFFSET;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public final int left, top, radius, cx, cy ;&lt;br /&gt;&lt;br /&gt;    public Circle(int left, int top, int radius) {&lt;br /&gt;        this.left = left;&lt;br /&gt;        this.top = top;&lt;br /&gt;        this.radius = radius;&lt;br /&gt;        cx = left + radius;&lt;br /&gt;        cy = top + radius;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    static class IntersectCircle extends Intersect&amp;lt;Circle, Circle&amp;gt;{&lt;br /&gt;        @Override public boolean intersect(Circle t, Circle c) {&lt;br /&gt;            int dx = c.cx - t.cx;&lt;br /&gt;            int dy = c.cy - t.cy;&lt;br /&gt;            double distance = Math.sqrt(dx*dx + dy*dy);&lt;br /&gt;            return (distance &amp;lt; t.radius + c.radius);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    static class IntersectRectangle extends Intersect&amp;lt;Circle, Rectangle&amp;gt;{&lt;br /&gt;&lt;br /&gt;        @Override public boolean intersect(Circle t, Rectangle r) {&lt;br /&gt;            return t.intRect(r.left, r.top, r.right, r.bottom);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    static class IntersectSquare extends Intersect&amp;lt;Circle, Square&amp;gt;{&lt;br /&gt;&lt;br /&gt;        @Override public boolean intersect(Circle t, Square s) {&lt;br /&gt;            return t.intRect(s.left, s.top, s.right, s.bottom);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override public String toString() {&lt;br /&gt;        return left + ", " + top + ", " + radius;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private int distance(int x, int y) {&lt;br /&gt;        int dx = cx - x;&lt;br /&gt;        int dy = cy - y;&lt;br /&gt;        return (int)Math.sqrt(dx*dx + dy*dy);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private boolean intRect(int left, int top, int right, int bottom) {&lt;br /&gt;        int lr = left - radius;&lt;br /&gt;        int rr = right + radius;&lt;br /&gt;        int tr = top - radius;&lt;br /&gt;        int br = bottom + radius;&lt;br /&gt;        if (cx &amp;lt;= lr || cx &amp;gt;= rr || cy &amp;lt;= tr || cy &amp;gt;= br)&lt;br /&gt;            return false;&lt;br /&gt;        if (cx &amp;lt;= left) {&lt;br /&gt;            if (cy &amp;lt;= top)&lt;br /&gt;                return distance(left, top) &amp;lt; radius;&lt;br /&gt;            if (cy &amp;gt;= bottom)&lt;br /&gt;                return distance(left, bottom) &amp;lt; radius;&lt;br /&gt;        } else if (cx &amp;gt;= right) {&lt;br /&gt;            if (cy &amp;lt;= top)&lt;br /&gt;                return distance(right, top) &amp;lt; radius;&lt;br /&gt;            if (cy &amp;gt;= bottom)&lt;br /&gt;                return distance(right, bottom) &amp;lt; radius;&lt;br /&gt;        }&lt;br /&gt;        return true;&lt;br /&gt;    }&lt;br /&gt;}&amp;nbsp;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-size: 130%; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Testing it out&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;First sketch some shapes and modify the test function from the implementing equals() article then code main to compare the shapes.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://3.bp.blogspot.com/_wwC0cvwYjJc/Syz3MJkUPRI/AAAAAAAAAGA/OU6FPe-iQEI/s1600-h/MultiShapes.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"&gt;&lt;img alt="" border="0" id="BLOGGER_PHOTO_ID_5416976239918595346" src="http://3.bp.blogspot.com/_wwC0cvwYjJc/Syz3MJkUPRI/AAAAAAAAAGA/OU6FPe-iQEI/s400/MultiShapes.png" style="cursor: pointer; display: block; height: 336px; margin: 0px auto 10px; text-align: center; width: 296px;" /&gt;&lt;/a&gt; By the way, I make no claims that the intersect algorithms are efficient or even correct: Let's see how this works out in the abstract base class Shape: &lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;public class TestIntersect {&lt;br /&gt;&lt;br /&gt;    public static void interPrint(Shape a, Shape b) {&lt;br /&gt;        String ac = a.getClass().getCanonicalName();&lt;br /&gt;        if (ac == null)&lt;br /&gt;            ac = "?";&lt;br /&gt;        else&lt;br /&gt;            ac = ac.substring(ac.indexOf('.') + 1);&lt;br /&gt;        String bc = b.getClass().getCanonicalName();&lt;br /&gt;        if (bc == null)&lt;br /&gt;            bc = "?";&lt;br /&gt;        else&lt;br /&gt;            bc = bc.substring(bc.indexOf('.') + 1);&lt;br /&gt;        System.out.println(ac + " " + a.toString() + " a intersect() " +&lt;br /&gt;               bc + " " + b.toString() + " b is " + a.intersect(b));&lt;br /&gt;        System.out.println("aoff: " + a.mtOffset() + " boff: " +&lt;br /&gt;           b.mtOffset()+ ", " + bc + " b intersect() " + ac + " a is " +&lt;br /&gt;           b.intersect(a) );&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void main(String[] args) {&lt;br /&gt;        Square square1 = new Square(10, 10, 40);&lt;br /&gt;        Circle circle1 = new Circle(30, 30, 20);&lt;br /&gt;        Rectangle rect1 = new Rectangle(40, 40, 20, 80);&lt;br /&gt;        interPrint(square1, circle1);&lt;br /&gt;        interPrint(circle1, rect1);&lt;br /&gt;        interPrint(square1, rect1);&lt;br /&gt;        System.out.println();&lt;br /&gt;        Square square2 = new Square(60, 120, 40);&lt;br /&gt;        Circle circle2 = new Circle(94, 85, 20);&lt;br /&gt;        Rectangle rect2 = new Rectangle(103, 5, 20, 80);&lt;br /&gt;        interPrint(square2, rect1);&lt;br /&gt;        interPrint(square2, circle2);&lt;br /&gt;        interPrint(circle2, rect2);&lt;br /&gt;        interPrint(square2, rect2);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Works O.K. Note that the Square's &lt;span style="font-family: courier;"&gt;mtOffset()&lt;/span&gt; is zero because it is initialized first. Changing instance construction order in &lt;span style="font-family: courier;"&gt;main()&lt;/span&gt; will change these values but functionality is not affected.  &lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;Square 10, 10, 40 a intersect() Circle 30, 30, 20 b is true&lt;/span&gt; &lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;aoff: 0, boff: 2. Circle intersect() Square is true&lt;/span&gt; &lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;Circle 30, 30, 20 a intersect() Rectangle 40, 40, 20, 80 b is true&lt;/span&gt; &lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;aoff: 2, boff: 1. Rectangle intersect() Circle is true&lt;/span&gt; &lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;Square 10, 10, 40 a intersect() Rectangle 40, 40, 20, 80 b is true&lt;/span&gt;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;aoff: 0, boff: 1. Rectangle intersect() Square is true&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;  &lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;Square 60, 120, 40 a intersect() Rectangle 40, 40, 20, 80 b is false&lt;/span&gt; &lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;aoff: 0, boff: 1. Rectangle intersect() Square is false&lt;/span&gt;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;Square 60, 120, 40 a intersect() Circle 94, 85, 20 b is false&lt;/span&gt; &lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;aoff: 0, boff: 2. Circle intersect() Square is false&lt;/span&gt; &lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;Circle 94, 85, 20 a intersect() Rectangle 103, 5, 20, 80 b is false&lt;/span&gt; &lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;aoff: 2, boff: 1. Rectangle intersect() Circle is false&lt;/span&gt; &lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;Square 60, 120, 40 a intersect() Rectangle 103, 5, 20, 80 b is false&lt;/span&gt;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 85%;"&gt;&lt;span style="font-family: arial;"&gt;aoff: 0, boff: 1. Rectangle intersect() Square is false&lt;/span&gt;&lt;/span&gt;  &lt;span style="font-size: 130%; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: 130%; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Summary&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-size: 130%; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt; &lt;br /&gt;Generic nested classes provide a way of declaring methods capable of multiple dispatch selection in standard Java. Without performance testing and as-is the technique looks faster than selection from a list of isA statements.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-2252973786659313177?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/2252973786659313177/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/12/how-to-code-multiple-dispatch-in-java.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/2252973786659313177'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/2252973786659313177'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/12/how-to-code-multiple-dispatch-in-java.html' title='How to code multiple dispatch in standard Java'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_wwC0cvwYjJc/Syz3MJkUPRI/AAAAAAAAAGA/OU6FPe-iQEI/s72-c/MultiShapes.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-5744678335641216583</id><published>2009-12-10T16:50:00.017Z</published><updated>2009-12-22T15:05:35.278Z</updated><title type='text'>Test</title><content type='html'>Decided on this syntax highlighter. Needed some typeface tweaking but has the great advantage that text can be copied without the line numbers if anyone would like to try some of my crazy code.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;public class Customer {&lt;br /&gt;&lt;br /&gt;    private String firstName;&lt;br /&gt;    private String lastName;&lt;br /&gt;    private Date birthday;&lt;br /&gt;    private String street;&lt;br /&gt;    private String city;&lt;br /&gt;    private String zipcode;&lt;br /&gt;&lt;br /&gt;    // follows the Eclipse generated result - two nulls are equal, but a&lt;br /&gt;    // couple of trivial static functions can take out many lines of code&lt;br /&gt;    public static boolean eqFields (Object a, Object b) {&lt;br /&gt;        if (a != null)&lt;br /&gt;            return a.equals(b);&lt;br /&gt;        else&lt;br /&gt;            return (b == null);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    protected boolean equalFields(Customer rhs) {&lt;br /&gt;        return eqFields(firstName, rhs.firstName) &amp;&amp;&lt;br /&gt;               eqFields(lastName, rhs.lastName) &amp;&amp;&lt;br /&gt;               eqFields(birthday, rhs.birthday) &amp;&amp;&lt;br /&gt;               eqFields(city, rhs.city) &amp;&amp;&lt;br /&gt;               eqFields(zipcode, rhs.zipcode);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public boolean equals(Object obj) {&lt;br /&gt;        if (this == obj) return true;&lt;br /&gt;        return (obj instanceof CustomerOrg &amp;&amp;&lt;br /&gt;                ((Customer)obj).equalFields(this));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static int hash(Object obj) {&lt;br /&gt;        return ((obj == null) ? 0 : obj.hashCode());&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override&lt;br /&gt;    public int hashCode() {&lt;br /&gt;        int result = 21 + hash(birthday);&lt;br /&gt;        result = result * 31 + hash(city);&lt;br /&gt;        result = result * 31 + hash(firstName);&lt;br /&gt;        result = result * 31 + hash(lastName);&lt;br /&gt;        result = result * 31 + hash(street);&lt;br /&gt;        return result * 31 + hash(zipcode);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-5744678335641216583?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/5744678335641216583/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/12/test.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/5744678335641216583'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/5744678335641216583'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/12/test.html' title='Test'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-232276059977668273</id><published>2009-12-06T20:57:00.023Z</published><updated>2009-12-15T22:07:05.016Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='overloading'/><category scheme='http://www.blogger.com/atom/ns#' term='Java'/><category scheme='http://www.blogger.com/atom/ns#' term='overriding equals java'/><title type='text'>The dangers of overloading</title><content type='html'>Posted the equals(Object) solution from my last blog on the &lt;a href="http://www.artima.com/forums/flat.jsp?forum=226&amp;amp;thread=259279&amp;amp;start=30&amp;amp;msRange=15"&gt;artima discussion&lt;/a&gt; for this topic. As a contributor demonstrated, if the protected field comparison methods are called from outside an instance some very strange results can be produced. The answer is of course that protected methods should not be called from outside a class even if Java's same-package rule permits access. Default access gives plenty of scope for any required kludge without ignoring this last vestige of encapsulation.&lt;br /&gt;&lt;br /&gt;These strange results should certainly discourage giving these methods public access or overloading an equals() with the class name, as seen in at least one published implementation. As things stand it is still quite possible to get the protected methods to return a symmetrical false when comparing the same object. All down to overloading, substitution and the aforementioned weak encapsulation but worth a look.&lt;br /&gt;&lt;br /&gt;The first thing to do is write a Point base and a ColoredPoint subclass, as in the &lt;a href="http://www.artima.com/lejava/articles/equality.html"&gt;artima article&lt;/a&gt;, but use the new equals() implementation rather canEqual. In the base-class field comparison is factored of to fEquals(Point) and equals(Object) calls the received object's version of fEquals.&lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;&lt;br /&gt;public class Point {&lt;br /&gt;&lt;br /&gt;    private final int x;&lt;br /&gt;    private final int y;&lt;br /&gt;&lt;br /&gt;    public Point(int x, int y) {&lt;br /&gt;        this.x = x;&lt;br /&gt;        this.y = y;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // accessors are optional for this discussion&lt;br /&gt;&lt;br /&gt;    @Override public boolean equals(Object obj) {&lt;br /&gt;        return (obj instanceof Point &amp;&amp;&lt;br /&gt;                ((Point)obj).fEquals(this) );&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    protected boolean fEquals(Point obj) {&lt;br /&gt;        return (this.x == obj.x &amp;&amp; this.y == obj.y);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    @Override public int hashCode() {&lt;br /&gt;        return (41 * (41 + getX()) + getY());&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Point can now be subclassed without overriding equals() and instances of all types will provide symmetry when compared for equality. ColouredPoint overrides equals() and overrides fEquals(Point) to return false - the required return comparing a ColoredPoint with a Point.&lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;&lt;br /&gt;public class ColoredPoint extends Point {&lt;br /&gt;&lt;br /&gt;    private final Color color;&lt;br /&gt;&lt;br /&gt;    public ColoredPoint(int x, int y, Color color) {&lt;br /&gt;        super(x, y);&lt;br /&gt;        this.color = color;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // ....................&lt;br /&gt;&lt;br /&gt;    @Override public boolean equals(Object obj) {&lt;br /&gt;        return (obj instanceof ColoredPoint &amp;&amp;&lt;br /&gt;                    ((ColoredPoint)obj).fEquals(this));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override protected boolean fEquals(Point obj) {&lt;br /&gt;        return false;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    protected boolean fEquals(ColoredPoint obj) {&lt;br /&gt;        return (this.color.equals(obj.color) &amp;&amp; super.fEquals(obj));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override public int hashCode() {&lt;br /&gt;        return (41 * super.hashCode() + color.hashCode());&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;ColoredPoint gets a fEquals(ColoredPoint) overloading and again equals() calls the received object's version. Using this technique we can write as many Point and ColoredPoint subclasses as we like that do or do not override equals().&lt;br /&gt;&lt;br /&gt;To show two references to the same object giving a symmetrical false the same ColoredPoint is assigned to a Point reference and a ColoredPoint reference:&lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;&lt;br /&gt; public static void main(String[] args) {&lt;br /&gt;     Point p1  = new Point(1, 1);&lt;br /&gt;     ColoredPoint cp1 = new ColoredPoint(1, 1, Color.PINK);&lt;br /&gt;     Point p2  = cp1;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;First do a check that equals(Object) is working O.K. Of the following the first two pairs should return symmetric false comparing a Point with a ColoredPoint. The last pair should get a symmetric true comparing the same ColoredPoint. A same-object check has not been put in equals so the full field comparison is done:&lt;br /&gt;&lt;pre class="brush: java; first-line: 15"&gt;&lt;br /&gt;     System.out.println("p1.equals(p2) is " + (p1.equals(p2)));&lt;br /&gt;     System.out.println("p2.equals(p1) is " + (p2.equals(p1)));&lt;br /&gt;     System.out.println("p1.equals(cp1) is " + (p1.equals(cp1)));&lt;br /&gt;     System.out.println("cp1.equals(p1) is " + cp1.equals(p1)));&lt;br /&gt;     System.out.println("p2.equals(cp1) is " + (p2.equals(cp1)));&lt;br /&gt;     System.out.println("cp1.equals(p2) is " + (cp1.equals(p2))+ "\n");&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Output is:&lt;blockquote dir="ltr" style="margin-right: 0px;"&gt;&lt;span style=";font-family:arial;font-size:85%;"  &gt;p1.equals(p2) is false&lt;/span&gt;&lt;br /&gt;&lt;span style=";font-family:arial;font-size:85%;"  &gt;p2.equals(p1) is false&lt;br /&gt;&lt;/span&gt;&lt;span style=";font-family:arial;font-size:85%;"  &gt;p1.equals(cp1) is false&lt;/span&gt;&lt;br /&gt;&lt;span style=";font-family:arial;font-size:85%;"  &gt;cp1.equals(p1) is false&lt;/span&gt;&lt;br /&gt;&lt;span style=";font-family:arial;font-size:85%;"  &gt;p2.equals(cp1) is true&lt;/span&gt;&lt;span style=";font-family:arial;font-size:85%;"  &gt;&lt;br /&gt;cp1.equals(p2) is true&lt;/span&gt;&lt;br /&gt;&lt;/blockquote&gt;&lt;br /&gt;Everything works as expected but now the overloaded fEquals() methods are tested:&lt;br /&gt;&lt;pre class="brush: java; first-line: 22"&gt;&lt;br /&gt;     System.out.println("p1.fEquals(p2) is " + (p1.fEquals(p2)));&lt;br /&gt;     System.out.println("p2.fEquals(p1) is " + (p2.fEquals(p1)) + "\n");&lt;/pre&gt;The p1 reference is a Point type that references a Point so Point's fEquals is called and the x, y fields are compared: true expected. The ClouredPoint argument referenced by p2 at runtime has no effect at compile or runtime. Runtime argument type never has any effect on which method gets called.&lt;br /&gt;&lt;br /&gt;For the second comparison the p2 reference is also a Point type. The compile time call is to fEquals(Point) but p2 references a ColoredPoint and its overriden version of fEquals(Point) is called at runtime: false expected, this method always returns false.&lt;br /&gt;&lt;br /&gt;Output is:&lt;blockquote dir="ltr" style="margin-right: 0px;"&gt;&lt;span style="font-size:85%;"&gt;&lt;span style="font-family:arial;"&gt;p1.fEquals(p2) is true&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;p2.fEquals(p1) is false&lt;/span&gt;&lt;/span&gt;&lt;/blockquote&gt;The next two comparisons behave in a similar way:&lt;br /&gt;&lt;pre class="brush: java; first-line: 24"&gt;&lt;br /&gt;     System.out.println("p1.fEquals(cp1) is " + (p1.fEquals(cp1)));&lt;br /&gt;     System.out.println("cp1.fEquals(p1) is " + (cp1.fEquals(p1)) + "\n");&lt;/pre&gt;p1.fEquals(cp1) behavior is the same as  p1.fEquals(p2), true expected. In cp1.fEquals(p1) gets a call to ColoredPoint's version of fEquals(Point): always false.&lt;br /&gt;&lt;br /&gt;Output is:&lt;blockquote dir="ltr" style="margin-right: 0px;"&gt;&lt;span style=";font-family:arial;font-size:85%;"  &gt;p1.fEquals(cp1) is true&lt;/span&gt;&lt;br /&gt;&lt;span style=";font-family:arial;font-size:85%;"  &gt;cp1.fEquals(p1) is false&lt;/span&gt;&lt;/blockquote&gt;The second result is obvious but now the references to the same ColoredPoint are compared:&lt;br /&gt;&lt;pre class="brush: java; first-line: 26"&gt;&lt;br /&gt;     System.out.println("p2.fEquals(cp1) is " + (p2.fEquals(cp1)));&lt;br /&gt;     System.out.println("cp1.fEquals(p2) is " + (cp1.fEquals(p2)));&lt;br /&gt;}&lt;/pre&gt;gets:&lt;blockquote dir="ltr" style="margin-right: 0px;"&gt;&lt;span style=";font-family:arial;font-size:85%;"  &gt;p2.fEquals(cp1) is false&lt;/span&gt;&lt;br /&gt;&lt;span style=";font-family:arial;font-size:85%;"  &gt;cp1.fEquals(p2) is false&lt;/span&gt;&lt;/blockquote&gt;cp1.fEquals(p2) is false is particularly unintuitive unless we remember that the runtime type of an argument has no effect on which method gets called - ever, unless said method is an exception handler that is.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-size:130%;" &gt;&lt;span style="font-family:arial;"&gt;The binary method problem&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Elsewhere multiple and predicate dispatching add another dimension to overridden methods by making the argument type/s direct execution to an appropriate method. A Java extension that supports predicate dispatching is [&lt;a href="http://www.cs.ucla.edu/%7Etodd/research/jpred.html"&gt;here&lt;/a&gt;] with a covering paper [&lt;a href="http://www.tinlizzie.org/%7Eawarth/papers/toplas09.pdf"&gt;pdf&lt;/a&gt;].&lt;br /&gt;&lt;br /&gt;One thing that multiple dispatching is good at is solving the binary method problem but at least a limited solution is possible in standard Java. Suppose we write a base class that has a method with an argument referencing an instance of the class or a same type array argument: a binary method. How can we allow for this method being overridden so that it works for instances and arguments of any subclass including those that have not yet been written and without changing code in the base class? The equals() implementation is a special case solution to the binary method problem using programmed double dispatching.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-size:130%;" &gt;&lt;span style="font-family:arial;"&gt;Diverse identifiers&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Overloading is simply a convenience that saves having to think up a new method name. It forms the basis of operator overloading but may not be appropriate when methods are subject to being overridden in a subclass. Overloading adds nothing to functionality and as shown above can get unwanted side effects when an overloaded method is overridden. Maybe we need to consider whether this kind of polymorphism is generally helpful or whether it only adds ambiguity in some and perhaps in many cases - not for the compiler of course but when trying to interpret someone else's code or our own at a later time.&lt;br /&gt;&lt;br /&gt;There is no reason why fEquals should not be given different identifiers in different classes, pointEquals(Point) and coloredPointEquals(ColoredPoint) for example. On the other hand doing this gets another common OOP problem: linkedColoredPointEquals(something) - huge identifiers that wrap code onto the next line. When implementing equals() there is never any scope for calling the protected method against a reference with an inappropriate nominal type. Perhaps all that is needed to provide better clarity is a more explicit overloaded method name, equalFields(...), for example.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-232276059977668273?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/232276059977668273/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/12/dangers-of-overloading.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/232276059977668273'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/232276059977668273'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/12/dangers-of-overloading.html' title='The dangers of overloading'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-6668286641141637597</id><published>2009-11-29T14:31:00.054Z</published><updated>2010-01-27T14:34:04.761Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='overriding equals'/><category scheme='http://www.blogger.com/atom/ns#' term='Java'/><title type='text'>Overriding equals(Object): an optimally correct solution</title><content type='html'>Overriding &lt;span style="font-family: courier new;"&gt;Object&lt;/span&gt;'s apparently innocuous &lt;span style="font-family: courier new;"&gt;equals(Object)&lt;/span&gt; method can be a source of difficulties. The first problem is that there appears to be no single implementation that meets all requirements. The second problem is the way that &lt;span style="font-family: courier new;"&gt;HashMap&lt;/span&gt;, the prime suspect for causing errors if the letter of the &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; specification is not met, uses equality to maintain its structure.&lt;br /&gt;&lt;br /&gt;When &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; is overridden the initial requirement is to ensure that the &lt;span style="font-family: courier new;"&gt;Object&lt;/span&gt; in &lt;span style="font-family: courier new;"&gt;equals(Object)&lt;/span&gt; belongs to a class that is comparable with the current object. Two different implementations can be found in publications from authorities on the subject. They have some utility but both cause problems if implemented outside their limited applicable usage. Neither can provide a correct implementation of &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; for all inheritance requirements in a class hierarchy. A third published implementation can supply an &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; with correct behaviour in the two most commonly required cases but brings a considerable execution overhead when &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; is overridden in a subclass.&lt;br /&gt;&lt;br /&gt;A simple &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; configuration is described that allows a class to have any of the three possible equality relationships with its super classes. For the two most commonly required relationships modifying the standard &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implementation found in Java library classes to provide correct behaviour is trivial, simply a matter of factoring-off field comparisons to a separate method. Overriding &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; in a subclass is similarly trivial. If no modification to equality is required the new class can be derived without any additional coding related to &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; functionality. The approach brings almost no penalty for execution efficiency and additional coding is minimal.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: medium;"&gt;&lt;br /&gt;&lt;span style="font-family: arial; font-weight: bold;"&gt;Background&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Overriding &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; allows a different view of object equality from &lt;span style="font-family: courier new;"&gt;Object&lt;/span&gt;'s same-object implementation to be introduced. Used with &lt;span style="font-family: courier new;"&gt;hashCode()&lt;/span&gt;, &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; also provides the basis for object inclusion, exclusion and retrieval from a &lt;span style="font-family: courier new;"&gt;HashMap&lt;/span&gt;, a fast storage and retrieval structure appropriate for many applications.&lt;br /&gt;&lt;br /&gt;Making an overridden &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; work according to plan brings two requirements: a well defined set of objects that the new method applies to and compliance with the so called &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; contract - in fact a definition of the required equality relationship between all objects. Its requirements are reflexivity, symmetry, transitivity, consistency and that a comparison with a null should always return false. These properties define an equality relationship found generally in most applications outside of quantum mechanics and we are on fairly safe ground.&lt;br /&gt;&lt;br /&gt;An exceptionally lucid expose of the &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; contract and discussion of problems with published &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implementations can be found at&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.angelikalanger.com/Articles/JavaSolutions/SecretsOfEquals/Equals.html"&gt;http://www.angelikalanger.com/Articles/JavaSolutions/SecretsOfEquals/Equals.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;The problem identified&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;The &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; problem occurs anywhere we want to derive a subclass that has a concrete superclass other than &lt;span style="font-family: courier new;"&gt;Object&lt;/span&gt;, for which &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; has already been overridden and add some fields that are significant when computing subclass equality.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://3.bp.blogspot.com/_wwC0cvwYjJc/SxKWrNaWIKI/AAAAAAAAAFg/cklEv6ngADM/s1600/Fig1.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"&gt;&lt;img alt="" border="0" id="BLOGGER_PHOTO_ID_5409551771504091298" src="http://3.bp.blogspot.com/_wwC0cvwYjJc/SxKWrNaWIKI/AAAAAAAAAFg/cklEv6ngADM/s400/Fig1.png" style="cursor: pointer; display: block; height: 332px; margin: 0px auto 10px; text-align: center; width: 400px;" /&gt;&lt;/a&gt;&lt;span style="font-family: arial;"&gt;&lt;span style="font-weight: bold;"&gt;Figure 1&lt;/span&gt;   &lt;span style="font-size: x-small;"&gt;A moot choice&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;As shown in Figure 1 - &lt;span style="font-family: courier new;"&gt;ClassA&lt;/span&gt;, we would probably like to inherit from an existing class getting all its methods and functionality without writing any code, taking advantage of normal OOP provision for code reuse. The requirement to override &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; may prevent this course because the standard &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implementation found in many Java library classes does not work in this situation.&lt;br /&gt;&lt;br /&gt;To get a better understanding of the problem we can formalize this requirement of an object model that makes object equality other than basic identity a property of all objects as:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;The first code reuse requirement:&lt;/span&gt; &lt;span style="font-style: italic;"&gt;ability to derive a class that declares zero or more new significant fields and is not a member of its superclass comparison set&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;It is apparent there are four possible requirements and this statement covers two of them. The remaining two are:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Second code reuse requirement:&lt;/span&gt; &lt;span style="font-style: italic;"&gt;ability to derive a class that declares no new significant fields and  is a member of its superclass comparison se&lt;/span&gt;t.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Third code reuse requirement:&lt;/span&gt; &lt;span style="font-style: italic;"&gt;ability to derive a class that declares new significant fields and  is a member of its superclass comparison set.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;We now need a definition for &lt;span style="font-style: italic;"&gt; comparison set&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;A comparison-set model&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;A comparison set is a set of classes having a root class for which instances of the root and some but possibly not all of its subclasses are compared for equality using significant fields declared or present in the root. For completeness we must also say that significant fields declared in a subclass may also figure in a comparison but this is an unusual condition satisfying the third code reuse requirement. When an object is compared with an object of a class not in its comparison set &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; is unable to make a meaningful comparison and must always return false. &lt;br /&gt;&lt;br /&gt;Figure 2 sketches a class hierarchy with classes in a comparison set coloured green. Other classes are not in the green set and supply a potential root for other comparison sets.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://1.bp.blogspot.com/_wwC0cvwYjJc/SxKXEiYunBI/AAAAAAAAAFo/WttMtah3T38/s1600/Fig+2.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"&gt;&lt;img alt="" border="0" id="BLOGGER_PHOTO_ID_5409552206631181330" src="http://1.bp.blogspot.com/_wwC0cvwYjJc/SxKXEiYunBI/AAAAAAAAAFo/WttMtah3T38/s400/Fig+2.png" style="cursor: pointer; display: block; height: 377px; margin: 0px auto 10px; text-align: center; width: 400px;" /&gt;&lt;/a&gt;&lt;span style="font-family: arial;"&gt;&lt;span style="font-weight: bold;"&gt;Figure 2&lt;/span&gt;    &lt;span style="font-size: x-small;"&gt;A comparison set&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;A class that is a descendant of &lt;span style="font-family: courier new;"&gt;Object&lt;/span&gt; and does not override &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; is in a comparison set with &lt;span style="font-family: courier new;"&gt;Object&lt;/span&gt; as its root. The particular contract of &lt;span style="font-family: courier new;"&gt;Object&lt;/span&gt;'s &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; - no two objects are equal, makes the standard implementation viable for overriding &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; in a direct subclass, A in Figure 2, but not in a sub classes B &amp;amp; C of a class in a derived comparison set. The standard implementation meets the first code reuse requirement in a class with no superclasses that have used it to override &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt;, elsewhere it fails.&lt;br /&gt;&lt;br /&gt;The Figure illustrates two important properties of comparison sets. Firstly, all classes in the set are descendants of a single root. The &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implemented in the root must include a condition that determines whether the argument in &lt;span style="font-family: arial;"&gt;equals(Object)&lt;/span&gt; is a member of the set of comparable objects for which a field comparison should be done or whether it is of another kind for which &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; should return false.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;The 'standard' equals() implementation&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;The standard implementation employs &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; the-root to exclude objects not in the comparison set. The &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; statement can appear in a number of different guises, as illustrated using a class that declares a value field with an overloaded &lt;span style="font-family: courier new;"&gt;==&lt;/span&gt; operator:&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt;"&gt;&amp;nbsp;   @Override public boolean equals(Object obj) {&lt;br /&gt;        return obj instanceof Root &amp;amp;&amp;amp;&lt;br /&gt;            value == ((Root) obj).value;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override public boolean equals(Object obj) {&lt;br /&gt;        if (obj instanceof Root) {&lt;br /&gt;            return (value == ((Root) obj).value);&lt;br /&gt;        }&lt;br /&gt;        return false;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override public boolean equals(Object obj) {&lt;br /&gt;        if (this == obj) return true;&lt;br /&gt;        if (! (obj instanceof Root)) return false;&lt;br /&gt;        return (value == ((Root) obj).value);&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;All configurations exclude instances of any class that is not a descendant of &lt;span style="font-family: courier new;"&gt;Root&lt;/span&gt; from field comparison and return false. The same-object check shown in the third configuration is of course optional and can be used in any implementation.&lt;br /&gt;&lt;br /&gt;Which brings us to the second property of comparison sets and the problem with the standard &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implementation: not all classes that are descendants of the &lt;span style="font-family: courier new;"&gt;Root&lt;/span&gt; are members of the same comparison set. The instanceof condition succeeds for instances of all subclasses irrespective of new fields. A superclass object can be found equal to a subclass object if fields declared in the superclass are equal to inherited fields in the subclass. Presenting the same superclass object to an overridden &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; in the subclass its &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; will reject the superclass object and return false.&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt;"&gt;&amp;nbsp;   @Override public boolean equals(Object obj) {&lt;br /&gt;        if (obj instanceof Subclass) {&lt;br /&gt;            Subclass sco = (Subclass) obj;&lt;br /&gt;            return ( .......... );&lt;br /&gt;        }&lt;br /&gt;        return false;&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;The symmetry requirement of object equality is broken and in the first case no proper equality assessment has been done making the result a nonsense.&lt;br /&gt;&lt;br /&gt;There are of course occasions when we want to derive a class from a superclass without overriding &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt;: the second code reuse requirement. A subclass might introduce a next field for example, a reference to an instance of the subclass so that a linked list of objects can be constructed. The standard implementation meets the second requirement. It fails when presented with a subclass instance that uses new fields to check equality and is not in the comparison set. It does not enable us to implement &lt;span style="font-family: courier new;"&gt;ClassA&lt;/span&gt; in Figure 1. Can an additional or modified condition be introduced to exclude instances of these classes from field comparison?&lt;br /&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;equals() using class comparison&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Another commonly seen &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implementation compares the runtime &lt;span style="font-family: courier new;"&gt;Class&lt;/span&gt; reference of the two objects to determine comparison set membership:&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt;"&gt;obj != null &amp;amp;&amp;amp; obj.getClass == this.getClass&lt;br /&gt;&lt;/pre&gt;replaces &lt;span style="font-family: courier new;"&gt;obj instanceof Root&lt;/span&gt; in the condition. It could be used to derive Figure 1 - &lt;span style="font-family: courier new;"&gt;ClassA&lt;/span&gt; if used in the existing and new classes but does not allow any further subclasses that belong to one or other comparison set to be derived. All objects that are not of the same class are excluded and &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; returns false for these objects.&lt;br /&gt;&lt;br /&gt;This means that superclass objects are excluded from subclass superclass comparisons and get a false return. If anything this characteristic is more dangerous in use than the &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; problem. When &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; is not overridden in a subclass its functionality is modified by proxy to get a constant false return for superclass objects. A person who derives the subclass and has not modified &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; may be left unaware of this side effect until the application fails at a later time. A class comparison &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implementation meets the &lt;span style="font-style: italic;"&gt;first code reuse &lt;/span&gt;requirement. It cannot meet the second.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;The third code reuse requirement&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Not surprisingly, overriding &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; from a concrete superclass is seldom seen in Java code but there is one pertinent and frequently quoted example: &lt;span style="font-family: courier new;"&gt;java.sql.Timestamp&lt;/span&gt;. This class is a &lt;span style="font-family: courier new;"&gt;java.util.Date&lt;/span&gt; subclass that overrides equals to include a &lt;span style="font-family: courier new;"&gt;nanos&lt;/span&gt; field. Comparing a &lt;span style="font-family: courier new;"&gt;Date&lt;/span&gt; with a &lt;span style="font-family: courier new;"&gt;Timestamp&lt;/span&gt; returns true if the dates match irrespective of the value of &lt;span style="font-family: courier new;"&gt;nanos&lt;/span&gt;. Comparing a &lt;span style="font-family: courier new;"&gt;Timestamp&lt;/span&gt; with a &lt;span style="font-family: courier new;"&gt;Date&lt;/span&gt; always returns false even with matching dates: 'because the nanos component of a date is unknown.'&lt;br /&gt;&lt;br /&gt;If &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; was overridden in both classes using the implementation proposed here there would be an open choice as to whether to make both comparisons return false or to allow a &lt;span style="font-family: courier new;"&gt;Timestamp&lt;/span&gt; to be equal to a &lt;span style="font-family: courier new;"&gt;Date&lt;/span&gt; if and only if its &lt;span style="font-family: courier new;"&gt;nanos&lt;/span&gt; field was zero (or any other single value). The methodology also allows a &lt;span style="font-family: courier new;"&gt;Timestamp&lt;/span&gt; to have symmetrical equality with a &lt;span style="font-family: courier new;"&gt;Date&lt;/span&gt; if dates match or if a &lt;span style="font-family: courier new;"&gt;Timestamp&lt;/span&gt; is within 500,000 nanos of a &lt;span style="font-family: courier new;"&gt;Date&lt;/span&gt; but these options break the&lt;span style="font-family: courier new;"&gt; equals()&lt;/span&gt; specification requirement for transitivity while the zero &lt;span style="font-family: courier new;"&gt;nanos&lt;/span&gt; option does not.&lt;br /&gt;&lt;br /&gt;Here the valid option where a &lt;span style="font-family: courier new;"&gt;Timestamp&lt;/span&gt; with a zero &lt;span style="font-family: courier new;"&gt;nanos&lt;/span&gt; field may be equal to a &lt;span style="font-family: courier new;"&gt;Date&lt;/span&gt; supplies an example of a third possible equality relationship between a sub and superclass and the third if seldom needed code reuse requirement.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Alternatives to the standard implementation&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;An alternative to producing a flawed &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; in a subclass using the standard or class comparison implementations is to use composition, as illustrated by Figure 1 - &lt;span style="font-family: courier new;"&gt;ClassB&lt;/span&gt;. Using composition to implement structural elements of a program or even a data type where it fits well is one thing. Being forced to use it to implement &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; is something else. Do this and we can be faced with another set of no-win choices: write a lot of methods that do nothing except call composed object methods or include a method that returns the composed object - a possible solution if the object is immutable, otherwise doing this is likely to cause more problems that it solves. There may still be a problem even when the returned object is a clone - the clone does not reflect legitimate modifications to the original.&lt;br /&gt;&lt;br /&gt;The standard &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implementation used in library classes leaves no satisfactory alternative to composition when &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; is overridden but otherwise it is not a desirable alternative.&lt;br /&gt;&lt;br /&gt;Taking on board the fact that neither of the commonly used implementations work satisfactorily an &lt;span style="font-style: italic;"&gt;artima&lt;/span&gt; article posts a working solution for overriding &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; to get two of the  code reuse requirements identified above:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.artima.com/lejava/articles/equality.html"&gt;http://www.artima.com/lejava/articles/equality.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;The third code reuse requirement is seldom needed and is therefore relatively unimportant but a problem with this implementation is that it uses a&lt;span style="font-family: courier new;"&gt; canEqual(Object)&lt;/span&gt; method that introduces an additional &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; check and execution overhead for all calls to &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; even when comparing same-class objects. Consequently it cannot be seen as an optimal replacement for the standard implementation that can be put in place as a matter of course to allow subclasses to be derived at a later time.&lt;br /&gt;&lt;br /&gt;Another downside is that the basic cost of a call doubles for an overridden equals in a subclass: &lt;span style="font-family: courier new;"&gt;super equals()&lt;/span&gt; is called to get superclass field comparison involving a second call to &lt;span style="font-family: courier new;"&gt;canEqual()&lt;/span&gt; and duplicate &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; tests. The primary indication for using hashed storage is to provide fast access making this implementation not ideal for specific use even when the requirement to override &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; is known in advance.&lt;br /&gt;&lt;br /&gt;The  &lt;span style="font-style: italic;"&gt;artima&lt;/span&gt; article shows a way forward and that a solution is possible but additional requirements to be addressed here are to devise an &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implementation with a minimal code footprint and execution overhead that can be used as a matter of course in any class that overrides &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt;. The implementation must allow fully working subclasses to be derived in all three cases where they may be required to meet OOP standards for code reuse.&lt;br /&gt;&lt;br /&gt;We have now identified the requirements that an optimal &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implementation must meet and can assess how the proposed alternative stands up.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Devising a solution&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Figure 3 shows an inheritance structure containing four comparison sets.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://4.bp.blogspot.com/_wwC0cvwYjJc/SxKXa0NAlyI/AAAAAAAAAFw/sQAV3Td5LFo/s1600/Fig+3.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"&gt;&lt;img alt="" border="0" id="BLOGGER_PHOTO_ID_5409552589370988322" src="http://4.bp.blogspot.com/_wwC0cvwYjJc/SxKXa0NAlyI/AAAAAAAAAFw/sQAV3Td5LFo/s400/Fig+3.png" style="cursor: pointer; display: block; height: 240px; margin: 0px auto 10px; text-align: center; width: 400px;" /&gt;&lt;/a&gt;&lt;span style="font-family: arial;"&gt;&lt;span style="font-weight: bold;"&gt;Figure 3&lt;/span&gt;   &lt;span style="font-size: x-small;"&gt;Green, red, yellow and blue comparison sets&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Here we consider a base class that is a concrete subclass of &lt;span style="font-family: courier new;"&gt;Object&lt;/span&gt;. Using an abstract base has only minor implications and then only if it declares significant fields. The simplest possible class will supply examples: one with a single integer field is used. The number of fields or even a complete audit of the current state of a data structure as used by &lt;span style="font-family: courier new;"&gt;HashMap&lt;/span&gt; has no bearing on the problem. This class is called &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; in the diagram and is the root of a green comparison set.&lt;br /&gt;&lt;br /&gt;With the exception of &lt;span style="font-family: courier new;"&gt;ZGreen&lt;/span&gt;,  &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; descendants in the green comparison set do not override &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt;. They introduce no new fields that figure in comparison and are comparable using the &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; inherited from &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt;. They can of course introduce other fields, the one on the left could be a &lt;span style="font-family: courier new;"&gt;LinkedGreen&lt;/span&gt; with a field referencing the next object in a list.&lt;br /&gt;&lt;br /&gt;Implementing these classes requires that the &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implementation satisfies the second requirement for code reuse: ability to derive a class that declares no new significant fields and  is a member of its superclass comparison set. From the Figure we can see that there is a secondary requirement - that the condition used to determine comparison set membership should include all possible descendants of the base on all branches.&lt;br /&gt;&lt;br /&gt;The standard implementation satisfies both these requirements using &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; the-base but now we come to the apparently conflicting code reuse requirement: ability to derive a class that declares zero or more new significant fields and is not a member of its superclass comparison set. The &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; in &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; inherited by green subclasses can do an initial assessment for comparison set membership using &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; or some similar isA condition but if it is going to make provision for derived comparison sets it must exclude instances of &lt;span style="font-family: courier new;"&gt;RedBase&lt;/span&gt;, &lt;span style="font-family: courier new;"&gt;YellowBase&lt;/span&gt; and &lt;span style="font-family: courier new;"&gt;BlueBase&lt;/span&gt; that supply the base class for new sets. All these classes are also &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; subclasses and instances will pass the initial assessment.&lt;br /&gt;&lt;br /&gt;This problem raised the question as to what additional isA or class comparison check could be put in &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; to exclude instances on the same or a different branch from the root. After some thought and deciphering of the contracts of various &lt;span style="font-family: courier new;"&gt;Class&lt;/span&gt; methods it was decided that there wasn't one. We could perhaps give all comparable objects an additional property, say &lt;span style="font-family: courier new;"&gt;Class comparisonBase()&lt;/span&gt; or a similar final field, but doing this adds additional coding and additional logic in &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;Otherwise only the received object can do the necessary checks but it was also found that when the decision on membership was passed to that object checking ancestry was no longer a requirement. The same is true when the received object's class has the third equality relationship, &lt;span style="font-family: courier new;"&gt;ZGreen&lt;/span&gt; in Figure 3, but as discussed below an additional isA check is then required.&lt;br /&gt;&lt;br /&gt;The following sections assess how this implementation fairs with regard to the criteria for minimum code size and effect on execution efficiency over the standard implementation.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Minimizing the code footprint&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;The requirement here was to develop an implementation that was altogether trivial to code and required a minimum of extra coding over the standard &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt;. &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; supplies a standard where differences are not overwhelmed by other code when the two implementations are shown side by side:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://3.bp.blogspot.com/_wwC0cvwYjJc/SxKXyIviEYI/AAAAAAAAAF4/6v420gWveUE/s1600/Listing.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"&gt;&lt;img alt="" border="0" id="BLOGGER_PHOTO_ID_5409552990021489026" src="http://3.bp.blogspot.com/_wwC0cvwYjJc/SxKXyIviEYI/AAAAAAAAAF4/6v420gWveUE/s400/Listing.png" style="cursor: pointer; display: block; height: 279px; margin: 0px auto 10px; text-align: center; width: 400px;" /&gt;&lt;/a&gt;&lt;br /&gt;Excluding braces from the calculation the difference amounts to the two extra lines of code used by the &lt;span style="font-family: courier new;"&gt;fEquals(GreenBase)&lt;/span&gt; method. The field comparison method can have any name even &lt;span style="font-family: courier new;"&gt;equals(GreenBase)&lt;/span&gt; but it is suggested that standardizing the name to &lt;span style="font-family: courier new;"&gt;fEquals&lt;/span&gt; will facilitate use of this implementation and that &lt;span style="font-family: courier new;"&gt;fEquals&lt;/span&gt; should be overloaded when &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; is overridden in descendants to maintain consistency in use.&lt;br /&gt;&lt;br /&gt;The extra coding is nothing compared with the complication of using composition to get a subclass equivalent and the chore of writing many do-nothing methods in a real life situation.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Minimizing the overhead&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;In &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; the &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implementation introduces the smallest possible overhead above the standard, only the cost of calling &lt;span style="font-family: courier new;"&gt;fEquals()&lt;/span&gt;. The initial task is to exclude &lt;span style="font-family: courier new;"&gt;equals(Object) &lt;/span&gt;arguments that are instances of any class not a &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; or a subclass. The &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; operator includes a check that the argument is not &lt;span style="font-family: courier new;"&gt;null&lt;/span&gt; and provides an economical solution:&lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;public class GreenBase&lt;br /&gt;{&lt;br /&gt;    private final  int value;&lt;br /&gt;&lt;br /&gt;    public GreenBase(int value) {&lt;br /&gt;        this.value = value;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public int getValue() {&lt;br /&gt;         return value;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override public boolean equals(Object obj) {&lt;br /&gt;        return obj instanceof GreenBase &amp;amp;&amp;amp;&lt;br /&gt;                ((GreenBase) obj).fEquals(this);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    protected boolean fEquals(GreenBase obj) {&lt;br /&gt;         return  ( value == obj.value );&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override public int hashCode() {&lt;br /&gt;        return 21 + value;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Having determined that the &lt;span style="font-family: courier new;"&gt;equals(Object)&lt;/span&gt; argument is a &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; or a subclass and therefore a type that has an &lt;span style="font-family: courier new;"&gt;fEquals(GreenBase)&lt;/span&gt; method the next step is to call the argument's version passing a reference to the current object. This call is the only addition to the overhead for an implementation with field comparison done inline. &lt;br /&gt;&lt;br /&gt;The decision on equality is passed to the received object. It is already known that the object is a &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; or a subclass. If the object's class is a member of the same comparison set it will have the same version of  &lt;span style="font-family: courier new;"&gt;fEquals(GreenBase)&lt;/span&gt;, which does the field comparison and returns the result, otherwise an overridden version simply returns &lt;span style="font-family: courier new;"&gt;false&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Deriving a new comparison set&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: courier new;"&gt;RedBase&lt;/span&gt; introduces a new significant field, is not comparable with a &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; or instances of any green subclass and forms the root of the red comparison set:&lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;public class RedBase extends GreenBase&lt;br /&gt;{&lt;br /&gt;    private final  long x;&lt;br /&gt;&lt;br /&gt;    public RedBase(int value, long x) {&lt;br /&gt;        super (value);&lt;br /&gt;        this.x = x;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public long getX() {&lt;br /&gt;         return x;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override public boolean equals(Object obj) {&lt;br /&gt;        return obj instanceof RedBase &amp;amp;&amp;amp;&lt;br /&gt;            ((RedBase) obj).fEquals(this);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    protected boolean fEquals(RedBase obj) {&lt;br /&gt;        return (x == obj.x &amp;amp;&amp;amp; super.fEquals(obj));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override protected boolean fEquals(GreenBase obj) {&lt;br /&gt;        return false;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override public int hashCode() {&lt;br /&gt;        return super.hashCode() * 31 + (int) (x ^ (x &amp;gt;&amp;gt;&amp;gt; 32));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;span style="font-family: courier new;"&gt;RedBase&lt;/span&gt; overrides &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; with a new &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; condition excluding instances of &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; and its other subclasses and calls a new &lt;span style="font-family: courier new;"&gt;fEquals(RedBase)&lt;/span&gt; overloading of the field comparison method on the received object.  &lt;span style="font-family: courier new;"&gt;fEquals(GreenBase)&lt;/span&gt; is overridden to return false.&lt;br /&gt;&lt;br /&gt;When a &lt;span style="font-family: courier new;"&gt;RedBase&lt;/span&gt; &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; receives a &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; or an instance of any of its other subclasses, including those that may have override &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt;, the &lt;span style="font-family: courier new;"&gt;instanceof RedBase&lt;/span&gt; condition fails and false is returned. When the &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; in a &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; or another subclass is passed a &lt;span style="font-family: courier new;"&gt;RedBase&lt;/span&gt; either its overriden &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; fails − it is a member of another derived comaprison set, or it is a member of the &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; comparison set and calls the object's overridden version of &lt;span style="font-family: courier new;"&gt;fEquals(GreenBase)&lt;/span&gt;. Either case gets a symmetric &lt;span style="font-family: courier new;"&gt;false&lt;/span&gt; result for the two comparisons − exactly what is required.&lt;br /&gt;&lt;br /&gt;Implementing classes that form the root of the other two comparison sets shown in Figure 3 follows the same pattern. &lt;span style="font-family: courier new;"&gt;BlueBase&lt;/span&gt; for example, inherits &lt;span style="font-family: courier new;"&gt;RedBase&lt;/span&gt;'s constant false &lt;span style="font-family: courier new;"&gt;fEquals(GreenBase)&lt;/span&gt;. It will override &lt;span style="font-family: courier new;"&gt;fEquals(RedBase)&lt;/span&gt; to return a constant false and implement a new &lt;span style="font-family: courier new;"&gt;fEquals&lt;/span&gt; overloading to deal with objects in the blue comparison set.&lt;br /&gt;&lt;br /&gt;The logic is completely straightforward, but now we move on to implementing the unusual equality relationship where a class declares a new field that is used for comparison with instances of the same class and its subclasses but comparison with a superclass and other subclasses in the comparison set is permitted.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Equality of the third kind&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: courier new;"&gt;ZGreen&lt;/span&gt; introduces a &lt;span style="font-family: verdana;"&gt;z&lt;/span&gt; field that is significant for equality. Comparison with instances of &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; and all other classes in the green comparison set is allowed.&lt;br /&gt;&lt;br /&gt;The only circumstance where doing this makes any sense is if &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; is seen as supplying some kind of default &lt;span style="font-family: verdana;"&gt;z&lt;/span&gt;. If &lt;span style="font-family: verdana;"&gt;z&lt;/span&gt; is a string the default might be &lt;span style="font-family: courier new;"&gt;""&lt;/span&gt; or &lt;span style="font-family: courier new;"&gt;null&lt;/span&gt;. If it is an integer it could be zero but the default can be any value from the range, yes even 42 is a possible candidate for an integer default. No approximate or wildcard value is permitted for the default or transitivity will no longer apply.&lt;br /&gt;&lt;br /&gt;A default of zero seems to make a little sense so &lt;span style="font-family: courier new;"&gt;ZGreen&lt;/span&gt; is implemented with an integer &lt;span style="font-family: verdana;"&gt;z&lt;/span&gt; field and all other objects in the green comparison set are seen as having &lt;span style="font-family: courier new;"&gt;z == 0&lt;/span&gt;:&lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;public class ZGreen extends GreenBase&lt;br /&gt;{&lt;br /&gt;   private final  int z;&lt;br /&gt;&lt;br /&gt;    public ZGreen(int value, int z) {&lt;br /&gt;        super (value);&lt;br /&gt;        this.z = z;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public int getZ() {&lt;br /&gt;         return z;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    @Override public boolean equals(Object obj) {&lt;br /&gt;        if (obj instanceof GreenBase) {&lt;br /&gt;            if (obj instanceof ZGreen)&lt;br /&gt;                return ((ZGreen) obj).fEquals(this);&lt;br /&gt;            return (z == 0 &amp;amp;&amp;amp; ((GreenBase) obj).fEquals(this));&lt;br /&gt;        }&lt;br /&gt;        return false;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    protected boolean fEquals(ZGreen obj) {&lt;br /&gt;        return (z == obj.z &amp;amp;&amp;amp; super.fEquals(obj));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    @Override protected boolean fEquals(GreenBase obj) {&lt;br /&gt;        return z == 0 &amp;amp;&amp;amp; super.fEquals(obj);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;In &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; the first &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; condition admits objects that are &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; or a subclass and false is returned for any other object. Here a second grouping of the comparison set is made to include instances of &lt;span style="font-family: courier new;"&gt;ZGreen&lt;/span&gt; and its subclasses using a second &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; comparison. Other objects that may or may not belong to the green comparison set are treated separately.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: courier new;"&gt;ZGreen&lt;/span&gt; arguments are dealt with by calling the object's &lt;span style="font-family: courier new;"&gt;fEquals(ZGreen)&lt;/span&gt;. For other types, a check for the default &lt;span style="font-family: verdana;"&gt;z&lt;/span&gt; value is made and if this succeeds the object's &lt;span style="font-family: courier new;"&gt;fEquals(GreenBase)&lt;/span&gt; is called. The local &lt;span style="font-family: courier new;"&gt;fEquals(GreenBase)&lt;/span&gt; is overridden to deal with direct calls from other objects in the comparison set when their &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; receives a &lt;span style="font-family: courier new;"&gt;ZGreen&lt;/span&gt; argument. Other &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; subclass objects will not be calling &lt;span style="font-family: courier new;"&gt;fEquals(GreenBase)&lt;/span&gt; because a &lt;span style="font-family: courier new;"&gt;ZGreen&lt;/span&gt; will fail their initial &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; condition.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: courier new;"&gt;hashCode()&lt;/span&gt; is not overridden - the inherited version returns a value based on the inherited &lt;span style="font-family: courier new;"&gt;value&lt;/span&gt; field so that &lt;span style="font-family: courier new;"&gt;GreenBase&lt;/span&gt; and &lt;span style="font-family: courier new;"&gt;ZGreen&lt;/span&gt; objects with a matching value both have the same hashcode.&lt;br /&gt;&lt;br /&gt;&lt;a href="" name="isa"&gt;&lt;/a&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;Implementing an isA comparison&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;In &lt;span style="font-family: courier new;"&gt;ZGreen&lt;/span&gt; the second &lt;span style="font-family: courier new;"&gt;instanceof&lt;/span&gt; comparison includes a redundant check that the &lt;span style="font-family: courier new;"&gt;Object &lt;/span&gt;argument is not null. It can be eliminated by substituting an isA comparison using the &lt;span style="font-family: courier new;"&gt;Class &lt;/span&gt;method &lt;span style="font-family: courier new;"&gt;isInstance(Object)&lt;/span&gt;.&lt;br /&gt;&lt;pre class="brush: java; first-line: 24"&gt;&amp;nbsp;   @Override public boolean equals(Object obj) {&lt;br /&gt;        if (obj instanceof GreenBase) {&lt;br /&gt;&lt;br /&gt;            // if obj isA ZGreen&lt;br /&gt;            if (ZGreen.class.isInstance(obj))&lt;br /&gt;                return ((ZGreen) obj).fEquals(this);&lt;br /&gt;            return (z == 0 &amp;amp;&amp;amp; ((GreenBase) obj).fEquals(this));&lt;br /&gt;        }&lt;br /&gt;        return false;&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;span style="font-size: xx-small;"&gt;&lt;span style="font-family: arial;"&gt;Interpreting the meaning of Class' isInstance() method is quite brain numbing. One trick is to correct the English in your head to what it actually means - '&lt;span style="font-weight: bold;"&gt;obj.getClass().hasInstance(this)&lt;/span&gt;' for example. Another trick is to read the statement right to left:&lt;span style="font-weight: bold;"&gt; this isInstance obj.getClass()&lt;/span&gt;. Failing these you can put your own &lt;span style="font-weight: bold;"&gt;isA()&lt;/span&gt; method in the base class - the only con is execution efficiency:&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;pre style="font-family: arial; font-size: 8pt;"&gt;public boolean isA(Object obj) {&lt;br /&gt;        if (obj == null) return false;      // optional check here - may be better done by caller&lt;br /&gt;        return obj.getClass().isInstance(this);&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;span style="font-size: medium; font-weight: bold;"&gt;&lt;span style="font-family: arial;"&gt;Summary&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;The &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; implementation shown here produces a correct comparison that complies with the &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; meta-contract for all of the three possible equality relationships that a subclass can have with a superclass. Analysis using the comparison-set model demonstrates that there are only three such relationships that &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; needs to support.&lt;br /&gt;&lt;br /&gt;It is suggested that any additional overhead from calling a factored-off field comparison method is insignificant in most cases and that the ability to produce subclasses with a fully functional overridden &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt;, allowing OOP code reuse without employing composition indicates that this implementation should be used as a matter of course when coding any class that overrides &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;There are other related topics that may be addressed in a later posting: using an abstract superclass, the &lt;span style="font-family: courier new;"&gt;HashMap put(K, V)&lt;/span&gt; gotcha and implications of the Liskov Substitution Principle. Currently all that needs to be said on the LSP is that the second Liskov and Wing paper excludes relationships between objects from general discussion but groups this aspect with other 'safety properties (nothing bad happens)'. Certainly the LSP does not appear to address anything beyond &lt;span style="font-family: courier new;"&gt;Object&lt;/span&gt;'s view of equality. It is down to us to make sure 'nothing bad happens' when &lt;span style="font-family: courier new;"&gt;equals()&lt;/span&gt; is overridden but it will certainly help if the implementation used works in the first place.&lt;br /&gt;&lt;br /&gt;Barbara Liskov, Jeannette M Wing -  A Behavioral Notion of Subtyping - ACM 1994&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;Test listing:&lt;/span&gt;&lt;br /&gt;&lt;pre class="brush: java; first-line: 10"&gt;public class TestEquals {&lt;br /&gt;&lt;br /&gt;    public static void eqPrint(Object a, Object b) {&lt;br /&gt;        String ac = a.getClass().getCanonicalName();&lt;br /&gt;        if (ac == null) ac = "?"; else ac = &lt;br /&gt;            ac.substring(ac.indexOf('.') + 1);&lt;br /&gt;        String bc = b.getClass().getCanonicalName();&lt;br /&gt;        if (bc == null) bc = "?"; else bc = &lt;br /&gt;            bc.substring(bc.indexOf('.') + 1);&lt;br /&gt;        System.out.println(ac + " a equals() " + bc + " b: " +&lt;br /&gt;            a.equals(b));&lt;br /&gt;        System.out.println(bc + " b equals() " + ac + " a: " + &lt;br /&gt;            b.equals(a));&lt;br /&gt;        System.out.println("Hashcodes are equal: " +&lt;br /&gt;                              (a.hashCode() == b.hashCode()));&lt;br /&gt;    }&lt;br /&gt;    public static void nl() {System.out.println();}&lt;br /&gt;    public static void main(String[] args) {&lt;br /&gt;        Object a = new GreenBase(42);&lt;br /&gt;        eqPrint(a, "");                     // false - false&lt;br /&gt;        eqPrint(a, new GreenBase(42));      // true  - true&lt;br /&gt;        eqPrint(a, new GreenSubA(42));      // true  - true&lt;br /&gt;        eqPrint(a, new GreenSubA(41));      // false - false&lt;br /&gt;        Object b = new GreenBase(42) {&lt;br /&gt;            String s = "local class";&lt;br /&gt;        };&lt;br /&gt;        eqPrint(a, b);                      // true  - true&lt;br /&gt;        nl();&lt;br /&gt;        a = new GreenSubA(42);&lt;br /&gt;        eqPrint(a, new GreenSubA(42));      // true - true&lt;br /&gt;        eqPrint(a, new GreenSubB(42));      // true - true&lt;br /&gt;        nl();&lt;br /&gt;        a = new RedBase(42, 7);&lt;br /&gt;        eqPrint(a, new RedBase(42, 7));     // true  - true&lt;br /&gt;        eqPrint(a, new RedBase(41, 7));     // false - false&lt;br /&gt;        eqPrint(a, new GreenBase(42));      // false - false&lt;br /&gt;        eqPrint(a, new GreenSubA(42));      // false - false&lt;br /&gt;        nl();&lt;br /&gt;        a = new ZGreen(42, 0);&lt;br /&gt;        eqPrint(a, new GreenBase(42));      // true  - true&lt;br /&gt;        eqPrint(a, new GreenSubA(42));      // true  - true&lt;br /&gt;        eqPrint(a, new ZGreenSubA(42, 0));  // true  - true&lt;br /&gt;        eqPrint(a, new GreenSubA(41));      // false - false&lt;br /&gt;        eqPrint(a, new RedBase(42, 0));     // false - false&lt;br /&gt;        eqPrint(a, new RedSubA(42, 0));     // false - false&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static class GreenBase {&lt;br /&gt;&lt;br /&gt;        private final int value;&lt;br /&gt;&lt;br /&gt;        public GreenBase(int value) {&lt;br /&gt;            this.value = value;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public int getValue() {&lt;br /&gt;            return value;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        @Override public boolean equals(Object obj) {&lt;br /&gt;            return obj instanceof GreenBase &amp;amp;&amp;amp;&lt;br /&gt;                    ((GreenBase) obj).fEquals(this);&lt;br /&gt;        }&lt;br /&gt;        protected boolean fEquals(GreenBase obj) {&lt;br /&gt;            return (value == obj.value);&lt;br /&gt;        }&lt;br /&gt;        @Override public int hashCode() {&lt;br /&gt;            return 21 + value;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static class GreenSubA extends GreenBase {&lt;br /&gt;        GreenSubA next;&lt;br /&gt;        public GreenSubA(int value) {&lt;br /&gt;            super (value);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    public static class GreenSubB extends GreenBase {&lt;br /&gt;        GreenSubB next;&lt;br /&gt;        public GreenSubB(int value) {&lt;br /&gt;            super (value);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static class RedBase extends GreenBase {&lt;br /&gt;&lt;br /&gt;        private final long x;&lt;br /&gt;&lt;br /&gt;        public RedBase(int value, long x) {&lt;br /&gt;            super(value);&lt;br /&gt;            this.x = x;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public long getX() {&lt;br /&gt;            return x;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        @Override public boolean equals(Object obj) {&lt;br /&gt;            return obj instanceof RedBase &amp;amp;&amp;amp;&lt;br /&gt;                    ((RedBase) obj).fEquals(this);&lt;br /&gt;        }&lt;br /&gt;        protected boolean fEquals(RedBase obj) {&lt;br /&gt;            return (x == obj.x &amp;amp;&amp;amp; super.fEquals(obj));&lt;br /&gt;        }&lt;br /&gt;        @Override protected boolean fEquals(GreenBase obj) {&lt;br /&gt;            return false;&lt;br /&gt;        }&lt;br /&gt;        @Override public int hashCode() {&lt;br /&gt;            return super.hashCode() * 31 + (int) (x ^ (x &amp;gt;&amp;gt;&amp;gt; 32));&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static class RedSubA extends RedBase {&lt;br /&gt;        RedSubA next;&lt;br /&gt;        public RedSubA(int value, long x) {&lt;br /&gt;            super(value, x);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static class ZGreen extends GreenBase {&lt;br /&gt;&lt;br /&gt;        private final int z;&lt;br /&gt;&lt;br /&gt;        public ZGreen(int value, int z) {&lt;br /&gt;            super(value);&lt;br /&gt;            this.z = z;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public int getZ() {&lt;br /&gt;            return z;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        @Override public boolean equals(Object obj) {&lt;br /&gt;            if (obj instanceof GreenBase) {&lt;br /&gt;                if (obj instanceof ZGreen) {&lt;br /&gt;                    return ((ZGreen) obj).fEquals(this);&lt;br /&gt;                }&lt;br /&gt;                return (z == 0 &amp;amp;&amp;amp; ((GreenBase) obj).fEquals(this));&lt;br /&gt;            }&lt;br /&gt;            return false;&lt;br /&gt;        }&lt;br /&gt;        protected boolean fEquals(ZGreen obj) {&lt;br /&gt;            return (z == obj.z &amp;amp;&amp;amp; super.fEquals(obj));&lt;br /&gt;        }&lt;br /&gt;        @Override protected boolean fEquals(GreenBase obj) {&lt;br /&gt;            return z == 0 &amp;amp;&amp;amp; super.fEquals(obj);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static class ZGreenSubA extends ZGreen {&lt;br /&gt;        ZGreenSubA next;&lt;br /&gt;        public ZGreenSubA(int value, int z) {&lt;br /&gt;            super(value, z);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-6668286641141637597?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/6668286641141637597/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/11/overriding-equalsobject-optimally.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/6668286641141637597'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/6668286641141637597'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/11/overriding-equalsobject-optimally.html' title='Overriding equals(Object): an optimally correct solution'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_wwC0cvwYjJc/SxKWrNaWIKI/AAAAAAAAAFg/cklEv6ngADM/s72-c/Fig1.png' height='72' width='72'/><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-8779730581976765223</id><published>2009-06-22T14:14:00.011+01:00</published><updated>2009-06-23T20:39:59.187+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Processing NetBeans copy paste'/><title type='text'>Using Processing in NetBeans  (6.5)</title><content type='html'>Boyd mentioned passing a reference to the current PApplet to separate classes from a Processing app. For anyone who has not yet tried combining Processing and NetBeans, points I have noted are here - there may be better alternatives. This post shows an example that implements a clipboard Copy and Paste subsystem. The code can be used in any processing application. Three variants are discussed: implementation as an inner class in a NetBeans (or PDE) environment, as a separate class in NetBeans and, using the resulting .jar from the Processing IDE (PDE). Initially a NetBeans Processing application is needed.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Creating a NetBeans Processing app.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;1) In NetBeans make a New project, say 'Processing Template', with Create Main Class say 'processing.ProcessingApp'. (if you change the package name in the wizard, the package is created OK but the &lt;span style="font-family: courier new;"&gt;package processing;&lt;/span&gt; statement may be missing from the listing: just type it in)&lt;br /&gt;&lt;br /&gt;2) Right click on the Libraries node in the project tree: Add JAR/folder, navigate to the folder where Processing core.jar is located, ...\processing-1.0.2-expert\ processing-1.0.2-expert\lib on my system. Select 'core.jar', and Open.&lt;br /&gt;&lt;br /&gt;3) Modify the class ProcessingApp as shown:&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt; background-color: rgb(244, 244, 244);"&gt;&lt;br /&gt;package processing;&lt;br /&gt;&lt;br /&gt;import processing.core.*;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; *&lt;br /&gt; * @author Martin Humby&lt;br /&gt; */&lt;br /&gt;public class ProcessingApp  extends PApplet {&lt;br /&gt;&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;      PApplet.main(new String[]{"processing.ProcessingApp"});&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   // Code that can optionally be copied to and compiled from the PDE goes here.&lt;br /&gt;   // The PDE only requires explicit import of packages it does not import&lt;br /&gt;   // implicitly: import java.awt.datatransfer and java.awt.image for the example &lt;br /&gt;   // below. Duplicating implicit imports is OK, for the standard imports&lt;br /&gt;   // that is. The PDE does not like public void setup() { } - delete public&lt;br /&gt;&lt;br /&gt;} // end of ProcessingApp&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Note that the string literal in main() must match the package name and class name. If you use Copy, Paste - Refactor to get a version copy and want to be able to run the copy, refactor does not modify the string and the new package and/or class-name must be changed by hand (otherwise the copy runs the current version of the original - confusing!).&lt;br /&gt;&lt;br /&gt;To get a slightly more convenient way of accessing the library path to core.jar, select Tools - Libraries from the NetBeans menu bar. New Library, Library Name: 'Processing', Library Type: Class Libraries. Make sure Processing is selected in the Libraries tree and do Add JAR/Folder as in 2) above. Now right click the Libraries node for the project select Add Library. Scroll down the list of Global Libraries and select Processing.&lt;br /&gt;&lt;br /&gt;Making the outline shown above a module template or plugin that can be installed into the IDE appears to have disadvantages. Seems to me the easiest way to keep a framework for Processing apps. handy is simply to save the outline as a standard project. Open the outline and use right-click Copy from the project node to get and rename a new project complete with the core.jar path already set up. You can of course include other Processing libraries with the outline.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Passing an explicit PApplet&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;An inner class that might be factored off to a separate class is a Clipboard Copy and Paste subsystem. Hiding its implementation means passing the current PApplet instance to its Copy and Paste functions. Writing subsystem access methods and the inner class as static ensures a separate class can be got with minimum modifications. Here the static keyword excludes passing an implicit this reference to the inner class: same situation as in a separate class. A difference is that enclosing class static fields remain accessible without qualification. Need to put this in if a straight transfer is going to work, (g.format == PApplet.ARGB) for example, or add such qualifications later.&lt;br /&gt;&lt;br /&gt;To try this approach Copy the 'Processing Template' as a new project say 'Processing Clipboard' and modify the class ProcessingApp as shown. You can of course use Refactor to rename the class if you wish and modify the string in main() to suit.&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt; background-color: rgb(244, 244, 244);"&gt;&lt;br /&gt;package processing;&lt;br /&gt;&lt;br /&gt;import java.awt.*;&lt;br /&gt;import processing.core.*;&lt;br /&gt;import java.awt.datatransfer.*;&lt;br /&gt;import java.awt.image.BufferedImage;&lt;br /&gt;import java.io.IOException;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; *&lt;br /&gt; * @author Martin Humby&lt;br /&gt; */&lt;br /&gt;public class ProcessingApp extends PApplet {&lt;br /&gt;&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;      PApplet.main(new String[]{"processing.ProcessingApp"});&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   static final int WIDTH = 500;&lt;br /&gt;   static final int PANEL_HT = 160;&lt;br /&gt;   static final int HEIGHT = PANEL_HT + 500;&lt;br /&gt;   static final int DRAWING_HEIGHT = HEIGHT - PANEL_HT;&lt;br /&gt;   static final int PANEL_TOP = DRAWING_HEIGHT;&lt;br /&gt;&lt;br /&gt;   public void setup() {&lt;br /&gt;      size(WIDTH, HEIGHT);&lt;br /&gt;      background(255);&lt;br /&gt;&lt;br /&gt;      // include a panel below drawing area&lt;br /&gt;      fill(128);&lt;br /&gt;      rect(0, PANEL_TOP, WIDTH - 1, PANEL_HT - 1);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   // draw() is required to get keyboard monitoring apparently&lt;br /&gt;   public void draw() {&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public void keyReleased() {&lt;br /&gt;      // CTRL+C: Copy to Clipboard&lt;br /&gt;      if (key == 3) {&lt;br /&gt;         copyImageToClipboard(0, 0, width, height - PANEL_HT, this);&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      // CTRL+V: Paste Clipboard&lt;br /&gt;      if (key == 22) {&lt;br /&gt;         PImage img = getClipboardImage(this);&lt;br /&gt;         if (img == null)&lt;br /&gt;            return; // not an image on clipboard&lt;br /&gt;&lt;br /&gt;         // blank drawing area if required&lt;br /&gt;         background(255);&lt;br /&gt;&lt;br /&gt;         // paste image centred on area above panel&lt;br /&gt;         int w = img.width;&lt;br /&gt;         int h = img.height;&lt;br /&gt;         int dx = (width - w) / 2;&lt;br /&gt;         int dy = (height - PANEL_HT - h) / 2;&lt;br /&gt;         image(img, dx, dy);&lt;br /&gt;&lt;br /&gt;         // restore the panel area&lt;br /&gt;         fill(128);&lt;br /&gt;         rect(0, PANEL_TOP, WIDTH - 1, PANEL_HT - 1);&lt;br /&gt;      }&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   /////////////////////////////////////////////////////////////////////////////&lt;br /&gt;   //&lt;br /&gt;   //  COPY AND PASTE SUBSYSTEM&lt;br /&gt;   //&lt;br /&gt;&lt;br /&gt;   /**&lt;br /&gt;    * Clipboard copy and paste: the following references were used&lt;br /&gt;    * http://processing.org/hacks/hacks:clipboard&lt;br /&gt;    * http://www.devx.com/Java/Article/22326/0/page/1  et seq.&lt;br /&gt;    *&lt;br /&gt;    */&lt;br /&gt;&lt;br /&gt;   public static void copyImageToClipboard(int top, int left, int width,&lt;br /&gt;         int height, PApplet p) {&lt;br /&gt;&lt;br /&gt;      // could pass this.g directly but passing this for both functions gets&lt;br /&gt;      // consistency in use&lt;br /&gt;      PGraphics g = p.g;&lt;br /&gt;&lt;br /&gt;      // g is needed to get format&lt;br /&gt;      BufferedImage bImage = new BufferedImage(width, height, &lt;br /&gt;            (g.format == PApplet.ARGB) ?&lt;br /&gt;                         BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);&lt;br /&gt;      g.loadPixels();&lt;br /&gt;&lt;br /&gt;      // some explicit identifiers clarify setRGB() usage:&lt;br /&gt;      // setRGB(bImageX, bImageY, bothW, bothH, source[], srcOffset, sourceW);&lt;br /&gt;      bImage.setRGB(0, 0, width, height, g.pixels, left + top * g.width, g.width);&lt;br /&gt;&lt;br /&gt;      TransferablePImage imageSelection = new TransferablePImage(bImage);&lt;br /&gt;      Toolkit.getDefaultToolkit().&lt;br /&gt;              getSystemClipboard().setContents(imageSelection, null);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   // return a PImage rather than an awt.Image&lt;br /&gt;   public static PImage getClipboardImage(PApplet p) {&lt;br /&gt;&lt;br /&gt;      Transferable t =&lt;br /&gt;              Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);&lt;br /&gt;      try {&lt;br /&gt;         if (t != null &amp;&amp; t.isDataFlavorSupported(DataFlavor.imageFlavor)) {&lt;br /&gt;            BufferedImage bimg = (BufferedImage)&lt;br /&gt;                t.getTransferData(DataFlavor.imageFlavor);&lt;br /&gt;            int w = bimg.getWidth();&lt;br /&gt;            int h = bimg.getHeight();&lt;br /&gt;&lt;br /&gt;            // make it ARGB to be on the safe side - makes no difference&lt;br /&gt;            // unless clipboard image has some tranparency could be?&lt;br /&gt;            PImage pImg = p.createImage(w, h, PApplet.ARGB);&lt;br /&gt;            pImg.loadPixels();&lt;br /&gt;            bimg.getRGB(0, 0, w, h, pImg.pixels, 0, w);&lt;br /&gt;            pImg.updatePixels();&lt;br /&gt;            return pImg;&lt;br /&gt;         }&lt;br /&gt;      } catch (UnsupportedFlavorException e) {&lt;br /&gt;      } catch (IOException e) {&lt;br /&gt;      }&lt;br /&gt;      return null;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   static class TransferablePImage implements Transferable {&lt;br /&gt;&lt;br /&gt;      // the class-name makes more sense as a separate class&lt;br /&gt;      private Image image;  // an awt.Image&lt;br /&gt;&lt;br /&gt;      public TransferablePImage(Image image) {&lt;br /&gt;         this.image = image;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      public Object getTransferData(DataFlavor flavor)&lt;br /&gt;              throws UnsupportedFlavorException {&lt;br /&gt;         if (!flavor.equals(DataFlavor.imageFlavor)) {&lt;br /&gt;            throw new UnsupportedFlavorException(flavor);&lt;br /&gt;         }&lt;br /&gt;         return image;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      public boolean isDataFlavorSupported(DataFlavor flavor) {&lt;br /&gt;         return flavor.equals(DataFlavor.imageFlavor);&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      public DataFlavor[] getTransferDataFlavors() {&lt;br /&gt;         // in some cases there may be more than one flavour?&lt;br /&gt;         return new DataFlavor[]{DataFlavor.imageFlavor};&lt;br /&gt;      }&lt;br /&gt;   }&lt;br /&gt;} // end of ProcessingApp&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;To test it open say Paint and load an image. Copy a selection smaller than 500 x 500, and paste to the Processing app. Copy and paste it back to Paint - the white border now surrounds the pasted area.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Factoring off the Clipboard Subsystem&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;It is optional whether a separate TransferablePImage class is put in a new package but doing this will make life easier if you want to use it from the Processing IDE. Right click Source Packages - New - Java Package, 'utilities' then&lt;br /&gt;utilities - New - Java Class -  'TransferablePImage'.&lt;br /&gt;&lt;br /&gt;Copy the inner class to the new file and modify it copying the subsystem interface methods as static class methods:&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt; background-color: rgb(244, 244, 244);"&gt;&lt;br /&gt;package utilities;&lt;br /&gt;&lt;br /&gt;import java.awt.*;&lt;br /&gt;import java.awt.datatransfer.*;&lt;br /&gt;import java.awt.image.BufferedImage;&lt;br /&gt;import java.io.IOException;&lt;br /&gt;import processing.core.*;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * Copy or paste Processing PImage to / from system clipboard&lt;br /&gt; *&lt;br /&gt; * @author Martin Humby&lt;br /&gt; */&lt;br /&gt;public class TransferablePImage  implements Transferable{&lt;br /&gt;&lt;br /&gt;   private Image image;&lt;br /&gt;&lt;br /&gt;   public TransferablePImage(Image image) {&lt;br /&gt;      this.image = image;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   // static methods now part of class&lt;br /&gt;   &lt;br /&gt;   public static void copyImageToClipboard(int top, int left, int  width,&lt;br /&gt;         int height, PApplet p) {&lt;br /&gt;&lt;br /&gt;        ... body as inner class&lt;br /&gt;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public static PImage getClipboardImage(PApplet p) {&lt;br /&gt;&lt;br /&gt;        ... body as inner class&lt;br /&gt;&lt;br /&gt;   }&lt;br /&gt;   &lt;br /&gt;   ... other methods as inner class&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;To test the new class make a copy of ProcessingApp, say ProcessingApp1, using copy and paste to the processing package. Do not forget to change the class name in the string literal! Add import utilities.TransferablePImage;  Delete the COPY AND PASTE SUBSYSTEM. Modify lines that call Copy and Paste to:&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt; background-color: rgb(244, 244, 244);"&gt;&lt;br /&gt;TransferablePImage.copyImageToClipboard(0, 0, width, height - PANEL_HT, this);&lt;br /&gt;&lt;br /&gt;PImage img = TransferablePImage.getClipboardImage(this);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Optionally delete ProcessingApp1 imports that are no longer used and proceed as before.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Using TransferablePImage from the PDE&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Create a new NetBeans project 'processing utilities' with Create Main Class unchecked. Fix up the libraries path to core.jar. Copy and Paste the utilities package from its current location to the new project's Source Packages node. Build the project: the location of the resulting processing_utilities.jar file is shown in the NetBeans Output window.&lt;br /&gt;&lt;br /&gt;Make a new folder called maybe 'jars'. A good place could be in the default My Docments\Processing folder. Copy the processing_utilities.jar file to the new folder. Open the Processing IDE and make a new Sketch. Copy in the code from ProcessingApp1.java from after the main() method. Do not include the last curly bracket that belongs to the enclosing class. Delete public from the setup() method.&lt;br /&gt;&lt;br /&gt;From the PDE menu bar select Sketch - Add File... navigate to the 'jars' folder and open processing_utilities.jar. The IDE reports 'One file added to the sketch.' No import statement is required and putting one in gets a compilation error. Run the sketch - the result should be identical to the NetBeans version. You can of course include several other classes in processing_utilities.&lt;br /&gt;&lt;br /&gt;For more on this subject see http://dev.processing.org/libraries/&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Summary&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Most code that compiles in the Processing IDE will compile in NetBeans with a PApplet wrapper and fixed up imports. There are a few exceptions. The non-Java color data type is an integer and needs changing to int. A second minor but annoying problem is the fact that Java has the default type for floating point as double. Processing makes the type implied but overflow checked on compile (neither check for values effectively zero apparently).&lt;br /&gt;&lt;br /&gt;Processing: float h = 4.13566733e-15; Java: float h = 4.13566733e-15f; Compiler simplicity maybe but after inserting a few dozen 'f's you begin to wonder whether it generates float g = 42; as a promotion. Java of course insists that PApplet methods that get overridden have the same public access as in PApplet but adding this is trivial.&lt;br /&gt;&lt;br /&gt;Similarly, most code that will compile in NetBeans compiles in the PDE. To avoid problems particularly when there are errors in the code, delete public access for setup(). Processing is perfectly happy with anonymous classes, which may save a few lines of code here and there. Currently generics are not supported. A pity. I like Java generics. They seem to fit nicely with the object model without providing a sledgehammer capability for wholesale obfuscation. Of course, this opinion may be a reaction to an excess of _traits and spiky brackets elsewhere but generics could be useful to reduce code size in some applications. A set of minimalistic controls managed and drawn by Processing for example:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_wwC0cvwYjJc/Sj-FFagV-mI/AAAAAAAAAFY/RWSQW3FWt-Q/s1600-h/Painting1.png"&gt;&lt;img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 400px; height: 394px;" src="http://4.bp.blogspot.com/_wwC0cvwYjJc/Sj-FFagV-mI/AAAAAAAAAFY/RWSQW3FWt-Q/s400/Painting1.png" alt="" id="BLOGGER_PHOTO_ID_5350141210400258658" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;There is little problem implementing a tiny control management subsystem using a state machine: there are less than a dozen states for a complete set and some can be excluded - no drag and drop for example. Similarly, a single Control type with action and graphics closures, implemented as classes and assigned to its attributes on a mix and match basis, keeps coding to a minimum. Controls manage themselves for radio-button selection and which control gets input (focus). Problems come up when programmatic access to a control is needed - to modify text in controls that show drawing status and size for example.&lt;br /&gt;&lt;br /&gt;Arguably this is the wrong way to do it. Perhaps closures should monitor status in the wider environment of the enclosing PApplet but doing this means that controls that can otherwise be entirely passive require a specific action closure or active graphic to do the monitoring. A single line of code, in the draw() function say, can modify a passive control. Alternatively a new closure class is required to implement monitoring.&lt;br /&gt;&lt;br /&gt;Control action and graphic attributes are coresponding base classes. Access to a specific attribute means either retaining a reference to the control and casting attributes to their actual type or retaining a reference to the attribute itself. Neither way is ideal as far as code size and clarity goes. Generics can do the casting once for a control reference and all specific attribute types are then accessible directly through that reference. There must be other situations where using generics from the PDE could be useful.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-8779730581976765223?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/8779730581976765223/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/06/using-processing-in-netbeans-65.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/8779730581976765223'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/8779730581976765223'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/06/using-processing-in-netbeans-65.html' title='Using Processing in NetBeans  (6.5)'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/_wwC0cvwYjJc/Sj-FFagV-mI/AAAAAAAAAFY/RWSQW3FWt-Q/s72-c/Painting1.png' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-3777559665376960182</id><published>2009-04-28T12:28:00.001+01:00</published><updated>2009-04-28T12:32:41.643+01:00</updated><title type='text'>Chunk 37 Outline</title><content type='html'>&lt;span style="font-size:100%;"&gt;&lt;span style="font-family: arial;"&gt;Next step to apply abstraction and functional approach to drawing lines with special properties.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;Characteristics of line: start, end points and path between. Anything can happen along line as random or other factors are applied to it.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;Underlying path across a grid of pixels and problems drawing it: Bresenham's algorithm.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;Abstracting error-value checking to a closure - simple implementation, optimization.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;Writing a function to draw a line between any two points, any width with a colour gradient along its length: needs end points of lines normal to conceptual underlying line.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;Writing another closure to return maximum-width end-points of lines at points along underlying length. Problem: filling in missing pixels between adjacent lines due to jagged profile when they offset along underlying line.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;Program draws colour gradient lines.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;Applying similar closure approach to diverse grids: circular and random spaced grid using array.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;PROGRAM 3D grid and thistle-down blob drawn with colour grad lines, moves along its length.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: arial;"&gt;Mostly code: say 48 hours work, 2 weeks max. Time to post code on blogger????&lt;/span&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-3777559665376960182?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/3777559665376960182/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/04/chunk-37-outline.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/3777559665376960182'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/3777559665376960182'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/04/chunk-37-outline.html' title='Chunk 37 Outline'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-1883240396014700647</id><published>2009-04-09T20:26:00.007+01:00</published><updated>2009-06-22T21:02:11.907+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Processing randomSeed'/><title type='text'>In Search of Processings Lost</title><content type='html'>&lt;span style="font-size:100%;"&gt;&lt;span style="font-family:arial;"&gt;As you may have noticed, Processing programs that use random() and/or noise() and do not set the seed for these functions before they are called, create a different output for each run. The run that gets the superb effect is lost forever but setting seeds always gets the same old effect as the last time. To retain random creation and the capability of recreating a successful run it would nice if the value of seeds could be read at the beginning of a run and stored for future reference. Unfortunately this is not possible - the underlying Java Random class sets seed randomly from its () constructor and does not include a method for retrieving a value that can be used with setSeed().&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;A workaround is to generate a value for seed using a similar procedure to Random's, record it, and then pass it to a seed setter:&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;void setup() {&lt;br /&gt;   size(WIDTH, HEIGHT);&lt;br /&gt;   long seed = 8682522807148013L + System.nanoTime();&lt;br /&gt;   System.out.println(seed);&lt;br /&gt;   randomSeed(seed);&lt;br /&gt;   doDrawing();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;output: 8702777365341749&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-size:100%;"&gt;&lt;span style="font-family:arial;"&gt;If this run turns out to be the great one change setup() to&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;void setup() {&lt;br /&gt;   size(WIDTH, HEIGHT);&lt;br /&gt;//      long seed = 8682522807148013L + System.nanoTime();&lt;br /&gt;//      System.out.println(seed);&lt;br /&gt;   randomSeed(8702777365341749L);&lt;br /&gt;   doDrawing();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;identical graphic output is recreated. Otherwise, just continue with the original setup() version and hope for the best. The same seed generation method is appropriate for noiseSeed(). The seed calculation shown will avoid holes in the total sequence of values returned by nextLong() - if such exist and affect the 48 bit seed used by Random that is. &lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-1883240396014700647?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/1883240396014700647/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/04/in-search-of-processings-lost.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/1883240396014700647'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/1883240396014700647'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/04/in-search-of-processings-lost.html' title='In Search of Processings Lost'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-8000147762345386853</id><published>2009-03-26T21:19:00.013Z</published><updated>2009-04-02T20:38:48.092+01:00</updated><title type='text'>Drawing with Lines</title><content type='html'>&lt;span style="font-family:arial;"&gt;This Chapter examines the nature of lines and how they can be used to create art using the line drawing facilities provided by Processing. Initially we look at the broadest possible description of a line and then get down to the nitty-gritty of making a program produce a required result by drawing lines.&lt;br /&gt;&lt;br /&gt;Not all lines are straight. A geodesic, the shortest distance between two points on the surface of the Earth, is a curve. Add random noise to a line and it can take on an aspect of a lightning strike, flickering flames, a rough sea, rain falling on a lake and other representations of chaotic behaviour or liquid flow according to the frequencies present in the noise. Any kind of line, straight, curved or distorted, can suggest an edge, a boundary or a link between two locations.&lt;br /&gt;&lt;br /&gt;Alternatively we may want a simplified view where the purity of  straight lines or the intersections of many lines are used to represent underlying curvature or some more complex shape. A grid of lines can define a two or three dimensional space where equal spacing represents the world as we see it but other spacings can give the effect of non-linearity. We can show distances and dimensions that would otherwise be too small or too large to see.  We can also employ the additional dimensions of light, colour, hardness, discontinuity (dots and dashes) and blur to achieve the effect we want.&lt;br /&gt;&lt;br /&gt;There are few straight lines in nature and even fewer orthogonal straight lines. A straight line has its own special significance when used representationally. An icon of human-kind one might say.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://upload.wikimedia.org/wikipedia/commons/thumb/6/66/NEO_nazca_lines_big.jpg/436px-NEO_nazca_lines_big.jpg"&gt;&lt;img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer; width: 327px; height: 400px;" src="http://upload.wikimedia.org/wikipedia/commons/thumb/6/66/NEO_nazca_lines_big.jpg/436px-NEO_nazca_lines_big.jpg" alt="" border="0" /&gt;&lt;/a&gt;&lt;span style="font-size:100%;"&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="font-weight: bold;font-size:130%;" &gt; &lt;span style="font-family:arial;"&gt;&lt;span style="font-size:100%;"&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size:85%;"&gt;&lt;span style="font-family:arial;"&gt;&lt;span style="font-weight: bold;"&gt;&lt;/span&gt;Satelight image of the &lt;/span&gt;&lt;/span&gt;&lt;span style="font-weight: bold;font-family:arial;font-size:85%;"  &gt;nazca lines&lt;/span&gt;&lt;span style="font-size:85%;"&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;from Wikimedia Commons NASA/GSFC/MITI/ERSDAC/JAROS, and U.S./Japan ASTER Science Team&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-weight: bold;font-size:130%;" &gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style="font-family:times new roman;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="font-family:times new roman;"&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-8000147762345386853?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/8000147762345386853/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/03/drawing-with-lines.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/8000147762345386853'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/8000147762345386853'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/03/drawing-with-lines.html' title='Drawing with Lines'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-6705757814867478112</id><published>2009-03-26T18:39:00.019Z</published><updated>2009-04-07T13:14:56.895+01:00</updated><title type='text'>The Line Drawing Functions</title><content type='html'>&lt;span style="font-family:arial;"&gt;Having got to grips with coordinates, setting colours and suchlike you will probably find line drawing relatively simple. Unlike some less enlightened environments Processing has only a single line drawing function and three line attribute setters.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-family:arial;font-size:100%;"  &gt;The line() function&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;Line(), is overloaded for drawing in 2D and in 3D. A line function with four arguments draws a line on the picture plane, the screen for current purposes.&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;   line(x1, y1, x2, y2)&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;draws a line from the point (x1, y1) to (x2, y2).&lt;br /&gt;&lt;br /&gt;To draw in 3D we must first setup a 3D drawing environment. Two 3D environments are available and as detailed in XXXX they are invoked by passing an extra argument to the function that sets the window size at the start of the program. You can use either&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;  size(x, y, P3D);   or   size(x, y, OPENGL);&lt;br /&gt;&lt;/pre&gt;&lt;span style="font-family:arial;"&gt;size() can also be called with a P2D argument to get faster 2D drawing than the default JAVA2D environment provides: size(x, y, P2D). At the time of writing P2D did not support all the facilities of the default mode for line drawing. Try its effect using the simple line drawing program we come to in a moment and check the line drawing and attribute setter functions on the Processing website for current details.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;With a 3D environment in place use:&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;  line(x1, y1, z1, x2, y2, z2);&lt;br /&gt;&lt;/pre&gt;&lt;span style="font-family:arial;"&gt;to draw a line between points (1) and (2) in three dimensional space. The extra coordinates z1 and z2 are the distances of points behind the picture plane. Their depth back from the front face of the screen is another way of thinking about it. If a line is located behind the picture plane and/or tilted in the depth dimension, it will be shown shorter than its length drawn flat on the screen.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;The line() functions accept floating point values and can be called with floating point or integer coordinates. Fractional values are rounded to the nearest pixel but casting arguments to integer can be sometimes be useful to smooth jagged parallel line endings e.g:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;   line(floatX1, floatY1, (int)floatX2, (int)floatY2); // smooth endings at X2, Y2&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-family:arial;" &gt;Line attribute setters&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;Three functions set the 'style' of the line that will be drawn by the next and subsequent calls to line(). The effect of calling any one of these functions remains in place until the same function is called again. To be able to revert to a previous value we need to make sure the old values are stored. Line style setters and many other functions that modify the drawing environment have a corresponding variable in the current instance of  the Processing application interface, called 'g'. To store the current line colour, for example, we can write &lt;/span&gt;&lt;br /&gt;&lt;pre&gt;  int oldColour =  g.strokeColor.&lt;br /&gt;&lt;/pre&gt;&lt;span style="font-family:arial;"&gt;Accessing variables using 'dot' notation is discussed later, particularly in Chapter ZZ: Object Oriented Programming. To revert to the old colour write&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;  stroke(oldColour);&lt;br /&gt;&lt;/pre&gt;&lt;span style="font-family:arial;"&gt;The facility to store and to revert to old settings allows a section of code or a function to draw using settings applicable to the task in hand and restore old settings afterwards - an aid to abstraction discussed later in this Chapter in connection with parametric graphics.&lt;br /&gt;&lt;br /&gt;The stroke() line colour setter accepts the same colour and alpha opacity values as the other Processing colour setters detailed earlier in XXXXX. Two other setters affect line drawing: strokeWeight() sets line thickness,  strokeCap() the shape or relative location of the end of a line. The program in Listing CC.1 demonstrates the effect of the line style setters.&lt;/span&gt;&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt; background-color: rgb(244, 244, 244);"&gt;&lt;br /&gt;      /* set window size and drawing environment */&lt;br /&gt;&lt;br /&gt;   // declaring constants static final makes sure they &lt;br /&gt;   // cannot be altered by mistake later in the program&lt;br /&gt;   static final int WIDTH = 200;  &lt;br /&gt;   static final int HEIGHT = 200; &lt;br /&gt;   static final int OS = 20; // lines offset from edges &lt;br /&gt;&lt;br /&gt;   void setup() { &lt;br /&gt;      // size(WIDTH, HEIGHT, P2D); &lt;br /&gt;      // PD2 mode not fully functional in Processing 1.0.2&lt;br /&gt;      // so use: &lt;br /&gt;      size(WIDTH, HEIGHT);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   /* draw in continuous mode */&lt;br /&gt;   void draw() {&lt;br /&gt;      // fill the window with charcoal grey&lt;br /&gt;      background(0.25 * 255);&lt;br /&gt;       &lt;br /&gt;      /* draw a 45 deg line top-right to bottom-left */&lt;br /&gt;      // set line colour to greyscale white &lt;br /&gt;      stroke(255);&lt;br /&gt;      // set line width to 12 pixels&lt;br /&gt;      strokeWeight(15);&lt;br /&gt;      // make the ends of the line squared off&lt;br /&gt;      strokeCap(SQUARE); &lt;br /&gt;      // draw the line&lt;br /&gt;      line(WIDTH - 2*OS, 2*OS, 2*OS, HEIGHT - 2*OS);&lt;br /&gt;      &lt;br /&gt;      /* draw two lines same length, parallel to it */&lt;br /&gt;      // rounded ends&lt;br /&gt;      strokeCap(ROUND);&lt;br /&gt;      &lt;br /&gt;      /* draw a red line 20 pixels wide above */&lt;br /&gt;      strokeWeight(23);&lt;br /&gt;      stroke(255, 0, 0);  // colour red&lt;br /&gt;      line(WIDTH - 3*OS, OS, OS, HEIGHT - 3*OS);&lt;br /&gt;      &lt;br /&gt;      /* draw a green line 20 pixels wide below */&lt;br /&gt;      stroke(0, 255, 0);  // colour green&lt;br /&gt;      line(WIDTH - OS, 3*OS, 3*OS, HEIGHT - OS);&lt;br /&gt;      &lt;br /&gt;      /* draw a blue line 50% opaque, width 20,  &lt;br /&gt;         top-left to the mouse cursor */&lt;br /&gt;      stroke(25, 25, 255, 255 / 2);  &lt;br /&gt;      strokeWeight(25);&lt;br /&gt;      // extend line past cursor point&lt;br /&gt;      strokeCap(PROJECT); &lt;br /&gt;      line(30, 30, mouseX, mouseY);&lt;br /&gt;   }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-family:arial;" &gt;Listing CC.1&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_wwC0cvwYjJc/SdtDTuNFdKI/AAAAAAAAAFQ/kvdt7lughIY/s1600-h/Figure_1rev1.png"&gt;&lt;img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer; width: 211px; height: 232px;" src="http://1.bp.blogspot.com/_wwC0cvwYjJc/SdtDTuNFdKI/AAAAAAAAAFQ/kvdt7lughIY/s400/Figure_1rev1.png" alt="" id="BLOGGER_PHOTO_ID_5321921390767862946" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style=""&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;Figure CC.2  Listing CC.1 running.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;Running the program note the effect of the attribute setter functions strokeWeight() and strokeCap() for changing line thickness and the shape or relative location of the end of a line as shown in Figure CC.1. Use the mouse to move the blue line over the other lines and note alpha transparency generally and where the lines intersect. Graphics behind an area of transparent colour may appear lighter or darker according to relative brightness values. Try changing the blue line to white,  stroke(255, 255, 255, 255 / 2); colours behind are now lightened.&lt;/span&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-6705757814867478112?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/6705757814867478112/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/03/line-drawing-functions.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/6705757814867478112'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/6705757814867478112'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/03/line-drawing-functions.html' title='The Line Drawing Functions'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_wwC0cvwYjJc/SdtDTuNFdKI/AAAAAAAAAFQ/kvdt7lughIY/s72-c/Figure_1rev1.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-3122320926168705848</id><published>2009-03-26T18:27:00.006Z</published><updated>2009-04-05T01:42:41.511+01:00</updated><title type='text'>Parametric Grids</title><content type='html'>&lt;span style="font-family:arial;"&gt;&lt;br /&gt;The effect of drawing a single line tends to be minimal and it is more likely that many lines will be needed to produce a required effect. In this section we look at a strategy for doing this that extends the repetition facility provided by loops.&lt;br /&gt;&lt;br /&gt;Another name for arguments is parameters and parametric graphics is a common feature of vector graphics applications. Using this approach a drawing task is abstracted (taken out) from the main part of the program and done by passing arguments to a function that draws the graphic. Many similar objects can be drawn with different sizes, locations, colours, and other properties determined by values passed to arguments.&lt;br /&gt;&lt;br /&gt;Initially we experiment with parametric grids and to do this with a minimum of work the initial step is to set up a basic grid drawing program for testing them out. Optionally the basic structure can be extended to produce actual drawings that include grids. Listing CC.2 shows the outline:&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt; background-color: rgb(244, 244, 244);"&gt;&lt;br /&gt;  /* set window size and drawing environment */&lt;br /&gt;&lt;br /&gt;  static final int WIDTH = 900; &lt;br /&gt;  static final int HEIGHT = 600; &lt;br /&gt;&lt;br /&gt;  void setup() {&lt;br /&gt;     size(WIDTH, HEIGHT); // default environment&lt;br /&gt;     doDrawing();&lt;br /&gt;  }&lt;br /&gt; &lt;br /&gt;  /* draw the drawing */&lt;br /&gt; &lt;br /&gt;  void doDrawing() {&lt;br /&gt;     // charcole grey background, again!&lt;br /&gt;     background(0.25 * 255);&lt;br /&gt;     // white grid lines&lt;br /&gt;     stroke(255);&lt;br /&gt;     // one pixel wide&lt;br /&gt;     strokeWeight(1);&lt;br /&gt;    &lt;br /&gt;     // draw a grid with number of cells xCells * yCells&lt;br /&gt;     int xCells = 13;&lt;br /&gt;     int yCells = 19;&lt;br /&gt;     drawGrid(0, 0, WIDTH, HEIGHT, xCells, yCells, true);&lt;br /&gt;    &lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  void drawGrid(int left, int top, int width, int height, int  xCells,&lt;br /&gt;        int yCells, boolean drawOutline){&lt;br /&gt;    &lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-family:arial;" &gt;  Listing CC.2 &lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;As it stands the outline will compile and run but does nothing except opening a window with a grey background. Sections of functionality will be factored off using calls to drawGrid()to draw as many different grids as we require. Such power should be used carefully so the first thing is to decide exactly what we want a drawGrid() function to do and make sure all drawGrids variations we write do just that.&lt;br /&gt;&lt;br /&gt;Arguments left and top are where the top-left corner of the grid will be positioned. Width and height specify the size of the grid in pixels, xCells and yCells the number of areas the grid is divided into in the horizontal and vertical directions respectively. Cells are to be made to fit the grid exactly by distributing any odd pixels evenly across cell widths and heights. If draw outline is passed true a one pixel wide line is to be drawn around the grid within the size given. All this sounds complicated but is actually very easy when we divide up the work using functions.&lt;br /&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-3122320926168705848?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/3122320926168705848/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/03/grids-in-space.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/3122320926168705848'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/3122320926168705848'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/03/grids-in-space.html' title='Parametric Grids'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-4879309994189340455</id><published>2009-03-26T17:01:00.026Z</published><updated>2009-04-05T03:52:32.342+01:00</updated><title type='text'>Drawing grids in 2D</title><content type='html'>&lt;span style="font-family:arial;"&gt;&lt;br /&gt;The code for a 2D drawGrid() can be something like this:&lt;br /&gt;&lt;/span&gt;&lt;pre style="font-family: courier; font-size: 4pt; background-color: rgb(244, 244, 244);"&gt;&lt;br /&gt;void drawGrid(int left, int top, int width, int height, int  xCells,&lt;br /&gt;              int yCells, boolean drawOutline){&lt;br /&gt;&lt;br /&gt;   // precondition for drawing the grid&lt;br /&gt;   if (width &amp;lt;= 0 || height &amp;lt;= 0) return;&lt;br /&gt;         &lt;br /&gt;   // compute the coordinates of the rightmost an bottom pixels&lt;br /&gt;   int right = left + width - 1;&lt;br /&gt;   int bottom = top + height - 1;&lt;br /&gt;&lt;br /&gt;   // draw the grid&lt;br /&gt;   drawVertGrid(left, top, right, bottom, width, xCells);&lt;br /&gt;   drawHorzGrid(left, top, right, bottom, height, yCells);&lt;br /&gt;&lt;br /&gt;   if (drawOutline){&lt;br /&gt;      // save current line width&lt;br /&gt;      float curWeight = g.strokeWeight;&lt;br /&gt;      // draw outline with a line 1 pixel wide&lt;br /&gt;      strokeWeight(1);&lt;br /&gt;      line(left, top, right, top);&lt;br /&gt;      line(right, top, right, bottom);&lt;br /&gt;      line(right, bottom, left, bottom);&lt;br /&gt;      line(left, bottom, left, top);&lt;br /&gt;      // restore line width&lt;br /&gt;      strokeWeight(curWeight);&lt;br /&gt;   }&lt;br /&gt;} &lt;/pre&gt;&lt;span style="font-weight: bold;font-family:arial;" &gt; Listing CC.3&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-family:arial;font-size:100%;"  &gt;Preconditions for execution&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;Writing functions it is wise to check that all possible values passed as arguments can be dealt with by the code in the function body. What happens, for example, if drawGrid() is called with zero or negative dimensions passed to width and/or height?&lt;br /&gt;&lt;br /&gt;If we see there is a problem a number of options are available. In this case a fully justifiable option is to simply ignore it. We are not trying to create a flawless machine and an emergent property of a program may turn out to be a spectacular work of art. On the other hand, if the code simply does not work a lot of time can be wasted trying to track down the bug.&lt;br /&gt;&lt;br /&gt;Another option is to pass the problem on to other functions. Perhaps the grid will be drawn with all or part of it off the screen. This eventuality can be passed on for line() to deal with.&lt;br /&gt;&lt;br /&gt;The third option is to write code at the start of the function that checks input is within range. These checks are known as preconditions: execution of other code in the function body is conditional on the checks being passed. There are three ways of dealing with a failed precondition: the function can return immediately to the caller; likewise but it returns a Boolean or some other value indicating success or failure;  alternatively an error condition can be created. Java error conditions are dealt with by throwing and catching exception objects, certainly beyond the scope of this Chapter. For drawing grids a simple conditional return statement is appropriate:&lt;br /&gt;&lt;/span&gt;&lt;pre&gt;      if (width &lt;= 0 || height &lt;= 0) return;&lt;/pre&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;Note that other problems such as zero or negative numbers of cells are passed on to the grid-line drawing functions.&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-family:arial;" &gt;Minimizing coding&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;Another useful strategy is to avoid writing code that does the same thing more than once. This makes the code run faster but more importantly can make it shorter and easier to read. We are going to draw numerous lines from the left to the right of the grid and from its top to the bottom so compute right and bottom before doing anything else:&lt;br /&gt;&lt;/span&gt;&lt;pre&gt;      int right = left + width - 1;&lt;br /&gt;      int bottom = top + height - 1;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;The next task is to draw the gridlines, done by two functions:&lt;br /&gt;&lt;/span&gt;&lt;pre&gt;      drawVertGrid(left, top, width, bottom, xCells, constrain);&lt;br /&gt;      drawHorzGrid(left, top, right, height, yCells, constrain);&lt;/pre&gt;&lt;span style="font-family:arial;"&gt;Finally a one pixel wide outline is drawn around the grid if this option is set having first saved the current line thickness, as shown in Listing CC.3.  Drawing the outline, and in calls to the drawing functions, the values of right and bottom computed on entry save numerous calculations.&lt;br /&gt;&lt;br /&gt;So, you may be thinking, if working out this stuff early is such a good thing why not do it in the doDrawing() function, pass these values to drawGrid()and maybe make some savings in other functions called from doDrawing()? There are a few reasons for not doing this but the most important relates to abstraction. Working in doDrawing() we should not have to consider the needs of drawGrid() or any other functions called, only what they can do to get the drawing done in terms of the size, shape and location of the objects drawn.&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-family:arial;" &gt;Drawing uniform cells&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;The tasks to be done by the grid-line drawing functions are: check preconditions, compute cell size, initialise the drawing position to the first grid line and finally, loop while the drawing position is less than the last pixel, drawing each grid line and incrementing position by cell size. Coding these tasks to draw vertical grid lines gets:&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt; background-color: rgb(244, 244, 244);"&gt;&lt;br /&gt;void drawVertGrid(int left, int top, int right, int bottom, int width,&lt;br /&gt;                  int xCells){&lt;br /&gt;&lt;br /&gt;   // precondition: if negative or zero cells exit now&lt;br /&gt;   if (xCells &amp;lt;= 0) return;&lt;br /&gt;&lt;br /&gt;   // compute cell width&lt;br /&gt;   float cellWidth = (float)width / xCells;&lt;br /&gt;&lt;br /&gt;   if (cellWidth &amp;lt; 1)&lt;br /&gt;     cellWidth = 1:&lt;br /&gt;&lt;br /&gt;   for (float x = left + cellWidth; x &amp;lt; right; x += cellWidth){&lt;br /&gt;&lt;br /&gt;     // x is the x-coordinate of the vertical line drawn in the window&lt;br /&gt;     line(x, top, x, bottom);&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;There are two points to watch out for computing cellWidth. The first one is division by zero. Java and Processing allow division by zero for floating point calculations without throwing a fit but an INFINITY result is usually best avoided (do it with integers and a divide by zero exception is thrown). In this case a zero divisor has already been excluded by the precondition: xCells must be greater than zero. Negative and zero values for width were excluded by drawGrid() making certain that cellWidth is positive. If  cellWidth was zero or negative adding it to x in the loop would never make x equal to or greater than right and the loop would not exit.&lt;br /&gt;&lt;br /&gt;Writing mission critical software - perhaps designed to avoid crashing our lauch vehicle in a nearby swamp or bringing a spacecraft to a perfect landing two miles below the surface - it would be wise to do similar checks in both the caller and the called function. As things stand a single check will do nicely. Excluding a negative value for xCells in drawVertGrid() rather than drawGrid() includes the option that other versions of drawVertGrid() will process such values to get a particular visual effect.&lt;br /&gt;&lt;br /&gt;The second point is that Java’s multipurpose division operator returns an integer result when both operands are integers. The drawGrid() specification requires that cells fit the grid. To make this work, cell dimensions need to be floating point values so that when added together fractions of a pixel periodically add up to a whole one. The integer argument width is typecast to(float) getting a floating point result complete with any fractional part. Lastly, if cellWidth is purely fractional, the entire grid will consist of minutely overlapping lines and may take a while to draw. In this case cell width is set to unity.&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-family:arial;" &gt;&lt;br /&gt;The drawing loop&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;Using a for loop keeps lines of code to a minimum. You will recollect that the format of a for loop is generally:&lt;br /&gt;&lt;/span&gt;&lt;pre style="font-family: courier; font-size: 4pt;"&gt;&lt;br /&gt;for (initialize loop variable;&lt;br /&gt;   condition for entering or re-entering the loop;&lt;br /&gt;      action to be done at the end of each pass through the loop){&lt;br /&gt;&lt;br /&gt;// stuff to be done in the loop goes here&lt;br /&gt;&lt;br /&gt;} // end of the loop&lt;br /&gt;&lt;/pre&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;At the start of the loop a line at the left of the grid is not required so the loop variable x is declared and initialised to draw the first line at  left + cellWidth . Declaring the loop variable in the loop declaration makes it accessible only within the loop, a safety advantage over a while loop in many cases because its value after exit can be somewhat obscure.&lt;br /&gt;&lt;br /&gt;Java for loops are not the simple counting loops seen in some other languages. Basically a for loop provides a concise way of writing a while loop by filling in the items inside the round brackets. Ideally the condition for entry or re-entry should specify a range of loop variable values that allows access to the loop - not a single value that when reached by incrementing or decrementing the variable terminates looping: loop while x != right; x += cellWidth, for example. Using an inequality exit condition there is a danger that x will be initialized greater than right permitting unplanned entry or that, due to a fractional initial value and/or an increment greater than or smaller than unity, x  steps over an assumed exit value. Result: the loop loops-for-ever. The condition x &amp;lt; right avoids these problems.&lt;br /&gt;&lt;br /&gt;The last part of the for loop declaration is executed after each pass through the loop. Here it adds cellWidth to the loop variable using the shorthand += operator to take it to the coordinate of the next grid line (approximately). In this case 'stuff to be done in the loop' is simply to draw the current line going top to bottom. The function that draws horizontal grid lines is similar:&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt; background-color: rgb(244, 244, 244);"&gt;&lt;br /&gt;void drawHorzGrid(int left, int top, int right, int bottom, int height,&lt;br /&gt;                  int yCells){&lt;br /&gt;&lt;br /&gt;   // precondition: if negative or zero cells exit now&lt;br /&gt;   if (yCells &amp;lt;= 0) return;&lt;br /&gt;&lt;br /&gt;   // compute cell height&lt;br /&gt;   float cellHeight = (float)height / yCells;&lt;br /&gt;   if (cellHeight &amp;lt; 1)&lt;br /&gt;      cellHeight = 1;&lt;br /&gt;&lt;br /&gt;   for (float y = top + cellHeight; y &amp;lt; bottom; y += cellHeight){&lt;br /&gt;&lt;br /&gt;      // y is the y-coordinate of the horizontal line drawn in the window&lt;br /&gt;      line(left, y, right, y);&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-4879309994189340455?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/4879309994189340455/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/03/drawing-grids-in-2d.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/4879309994189340455'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/4879309994189340455'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/03/drawing-grids-in-2d.html' title='Drawing grids in 2D'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-5562546136300264739</id><published>2009-03-26T16:18:00.016Z</published><updated>2009-04-05T03:55:11.752+01:00</updated><title type='text'>Drawing some grids</title><content type='html'>&lt;span style="font-family:arial;"&gt;All done! Make a separate copy of  Listing CC.2 by starting a new sketch and pasting the code into the window. Replace the dummy drawGrid() stub with the one in Listing CC.3, type in the drawVertGrid() and drawHorzGrid() functions, save the file with a name of your choice and run the program.&lt;br /&gt;Try changing the number of cells in either or both directions by altering the variables shown in Listing CC.2, make the grid larger or smaller in either or both directions, change its left, top origin and so on. If you only want grid lines running in one direction pass zero for cells in that direction. Optionally, put additional calls in the Listing CC.2 code to draw several grids in different locations, perhaps with different colours and opacities using loops to change line style for calls to drawGrid(). Figure CC.3 shows an example.&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_wwC0cvwYjJc/SdVFzVyinlI/AAAAAAAAAEM/XZjBDjA0gJU/s1600-h/Figure_3.png"&gt;&lt;img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 400px; height: 263px;" src="http://3.bp.blogspot.com/_wwC0cvwYjJc/SdVFzVyinlI/AAAAAAAAAEM/XZjBDjA0gJU/s400/Figure_3.png" alt="" id="BLOGGER_PHOTO_ID_5320235283132882514" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;Figure CC.3 Effects produced by drawing multiple and overlapping grids.&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-family:arial;" &gt;&lt;br /&gt;Drawing unequal cell sizes&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;Grid line spacing can follow any rule: logarithmic, quadratic, cubic, Fibonacci, etc. or can be random. Another version of  drawVertGrid() draws grid lines with logarithmic spacing:&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;pre style="font-family: courier; font-size: 4pt; background-color: rgb(244, 244, 244);"&gt;&lt;br /&gt;void drawVertGrid(int left, int top, int right, int bottom, int width,&lt;br /&gt;                  int xCells){&lt;br /&gt;&lt;br /&gt;   if ( xCells &amp;lt;= 0 ) return;&lt;br /&gt;&lt;br /&gt;   int m = xCells + 1;&lt;br /&gt;   float logCells = log(m);&lt;br /&gt;   for (int i = 2; i &amp;lt;= m; i++) {&lt;br /&gt;     int x = left + round(log(i)/logCells * width);&lt;br /&gt;     line(x, top, x, bottom);&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;In this case the loop variable is an integer and values from 2 to m are submitted to the computation to get offsets from the grid's left coordinate. Working out line intervals relies on logm(x) = log(x) / log (m).  Log(1) is zero, the grid's left origin, so m is (numCells + 1). Alternatively you may wish to ignore these facts and just look at the nice dynamic that logarithmic spacing gets for any number of lines drawn across the face of a grid.&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_wwC0cvwYjJc/SdaF5_vO3uI/AAAAAAAAAEk/bfGKrhaFQZ0/s1600-h/Figure_4.png"&gt;&lt;img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 400px; height: 263px;" src="http://2.bp.blogspot.com/_wwC0cvwYjJc/SdaF5_vO3uI/AAAAAAAAAEk/bfGKrhaFQZ0/s400/Figure_4.png" alt="" id="BLOGGER_PHOTO_ID_5320587241193397986" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-family:arial;font-size:85%;"  &gt;Figure CC.4 &lt;/span&gt;&lt;span style="font-size:85%;"&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;Logarithmic and Circular Grid parametrics.&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:arial;"&gt;&lt;br /&gt;Using a rule more complex than logarithmic the easiest way to make cell sizes follow the drawGrid() specification for a specified number of cells with an exact fit to the grid is to compute relative sizes and store them them in an array. If predetermined relative sizes are needed to give an effect these values can be assigned when the array is created. The drawing loop simply uses the ratio between the sum of the sizes in the array and the dimension of the grid to work out line positions. Doing this needs slightly more code that the grid-line drawing functions we have investigated at so far and we can return to this variation later.&lt;br /&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-5562546136300264739?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/5562546136300264739/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/03/drawing-grid.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/5562546136300264739'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/5562546136300264739'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/03/drawing-grid.html' title='Drawing some grids'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_wwC0cvwYjJc/SdVFzVyinlI/AAAAAAAAAEM/XZjBDjA0gJU/s72-c/Figure_3.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-464656433343109986</id><published>2009-03-26T14:45:00.002Z</published><updated>2009-03-26T15:03:25.473Z</updated><title type='text'>Posting  Computer art and graphics section</title><content type='html'>Having wasted hours pasting text and graphics into the Blogger editor only to have have all the formatting collapse into bold italic decided to post Chunk 36 in bits.&lt;br /&gt;Will do this starting from the last section and blog title as headings.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-464656433343109986?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/464656433343109986/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/03/posting-computer-art-and-graphics.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/464656433343109986'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/464656433343109986'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/03/posting-computer-art-and-graphics.html' title='Posting  Computer art and graphics section'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-2287416002061877503</id><published>2009-03-16T17:25:00.008Z</published><updated>2009-03-23T14:15:12.680Z</updated><title type='text'>Sorting Blog</title><content type='html'>Time to try posting something more substantial. Here is one prepared earlier.&lt;br /&gt;&lt;br /&gt;This article discusses the merits and otherwise of comparison sorting algorithms in general use based on timings and comparison count data. It was found that performance of a fully optimized quicksort degraded when faced with so called median of three killer data compared with random ordered data but not to the extent that might have been expected. Mergesort was able to sort data with this configuration substantially faster than random data out performing all other algorithms tested and was only marginally slower than quicksort on random data. As noted elsewhere mergesort has an advantage over quicksort when there is any relationship between the key used to obtain an existing ordering and the required key and it is suggested that its additional space requirement is unlikely to be a problem where memory is not at an absolute premium. Mergesort sorts a 1,024,000 item list with a median of three killer configuration in less than 1/3 the time taken by a library function apparently engineered to deal with this type of data and appears to be a median of three killer-Killer.   &lt;h1 class="western" align="left"&gt;&lt;b&gt;&lt;i&gt;&lt;span style="font-family:Arial;"&gt;Comparison Sorting: The State of the Art&lt;/span&gt;&lt;/i&gt;&lt;/b&gt; &lt;/h1&gt;&lt;span style="font-family:times new roman;"&gt;One of the problems I have set myself currently is to implement an algorithm&lt;/span&gt; &lt;span style="font-family:times new roman;"&gt;to comparison sort a list of random ordered data faster than quicksort. That difficulty comes from a Delphi Magazine article [1] where I suggested that it could be done.  This blog reports findings from the article and examines relative performance of quicksort and mergesort to prepare for a look at sorting algorithms written in Java. You never know, something might just drop out.&lt;/span&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_wwC0cvwYjJc/ScVqdeURugI/AAAAAAAAADM/VxdqyZfzVL0/s1600-h/Sorting+Demo.png"&gt;&lt;img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 400px; height: 372px;" src="http://2.bp.blogspot.com/_wwC0cvwYjJc/ScVqdeURugI/AAAAAAAAADM/VxdqyZfzVL0/s400/Sorting+Demo.png" alt="" id="BLOGGER_PHOTO_ID_5315771989767600642" border="0" /&gt;&lt;/a&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;The main points of the Delphi article were that memory usage was no longer the critical factor it had once been for general sorting on PCs and workstations and that mergesort was the algorithm of choice for sorting certain large data sets. Naturally the scenario under consideration related to Delphi where heap management did not include compaction and the machine stack provided a low overhead location for a buffer, mostly irrelevant to Java but not so the other findings. A library class TList came with a Sort method that accepted a comparison function and used a concise but unoptimized version of quicksort. TList exposes its underlying dynamically allocated array as a read property so that any sorting method can be applied to it. &lt;/span&gt;&lt;/p&gt;&lt;div style="text-align: right;"&gt;&lt;span style="font-weight: bold;font-family:arial;font-size:85%;"  &gt;Mergesort beats quicksort even when carrying the full key . . . &lt;/span&gt;&lt;br /&gt;&lt;/div&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;The article quoted a case where a list in StaffNumber within Name order was extracted from a database and sorted -  StaffNumber within Name within DepartmentNumber. Numbers were integers and Name was a single-word string. Actual surnames from the UK were used, occurrence weighted based on some token occurrence data.  As a stable sort,  mergesort could re-sort the list on a single key. Around an 80% sort time reduction was found: mergesort on DepartmentNumber only vs. quicksort on the full key. &lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:times new roman;"&gt;An interesting point that came to light was that mergesort still showed better performance even when the full key was used by both algorithms.  As conjectured at the time and since confirmed, mergesort's stable characteristic reduced the number of times nested keys were accessed to decide a comparison. Timings for these unoptimized sorting algorithms running on a current desktop machine, maximum department size 500, are:&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_wwC0cvwYjJc/ScVX-kd-DRI/AAAAAAAAAC8/VWoTmozvLVg/s1600-h/Mag+Table.png"&gt;&lt;img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 400px; height: 60px;" src="http://4.bp.blogspot.com/_wwC0cvwYjJc/ScVX-kd-DRI/AAAAAAAAAC8/VWoTmozvLVg/s400/Mag+Table.png" alt="" id="BLOGGER_PHOTO_ID_5315751667633622290" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;Mergesort can beat quicksort hands down for many sorting tasks but for a data set with existing ordering unrelated to the required key quicksort has the edge.&lt;/span&gt;&lt;/p&gt;&lt;p  style="font-weight: bold;font-family:arial;"&gt;&lt;span style="font-size:130%;"&gt;Mergesort vs. Quicksort&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;Mergesort and quicksort  are the current algorithms of choice for in-memory comparison sorting. They both divide the list to be sorted into sublists and this approach makes adaption for multiprocessing relatively simple. Quicksort, devised by C.A.R. (Tony) Hoare [2] uses relocation of elements above or below a partition value, initially for the complete list and subsequently for each partitioned sublist. Mergersort, sometimes said to be based on an idea proposed by John von Neumann, uses repeated binary division of the list into sublists, sorts small sublists and merges adjacent sorted sublist pairs.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;Quicksort works in place and requires little additional storage but is not stable: relative locations of same key elements are modified. Stable variants of quicksort need storage areas outside the list and using a buffer smaller than the complete list will likely get worse performance than mergesort. Mergesort is inherently stable but an implementation that provides efficiency approximating to quicksort needs a buffer to store items during a merge. Merging with minimum element relocations and therefore best efficiency requires a buffer half the size of the complete list.&lt;br /&gt;&lt;/span&gt;&lt;/p&gt;&lt;p  style="font-weight: bold;font-family:arial;"&gt;&lt;span style="font-size:130%;"&gt;Quicksort Nemeses&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;Quicksort has an average time complexity of O(n log n): on average it will take 2n ln(n) comparisons to sort a list. But, if the heuristic for choosing a partition value or 'pivot' is to use the first element of the list, basic quicksort will use minimum (n&lt;sup&gt;2&lt;/sup&gt;  –  n) / 2 comparisons to sort a reverse order list or to check that an in-order list does not need any elements moving. This is O( n&lt;sup&gt;2&lt;/sup&gt; ) 'quadratic' complexity, characteristic of the most basic sorting algorithms. Sorting 10000 elements in reverse order takes around 49,995,000 comparisons as opposed to the 184,207 average. An obvious solution is not to use the first element. Why not  the middle element for example? The problem with setting the partition value in this way is that there will always be some list arrangements that get quadratic complexity.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;Various schemes have been proposed to select a good pivot, including random selection. The more complex a selection scheme the higher its overhead is likely to be and it is hard if not impossible to show that a particular scheme will get complete immunity for all possible input configurations. Median of three selection carries a low-overhead and appears to get superior partitioning for a wide range of list configurations [3]. Three elements are selected, generally the first middle and last element, compared and/or sorted. The median supplies the partition value. The quicksort that I need to beat in the Faster Than Quicksort game uses median of three engineered to get an average overhead of less than one comparison per sublist.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;In 1997 David Musser presented an analysis [4] that showed there were a significant number of list configurations that would drive a median of three selection quicksort quadratic: 'Median of Three Killers'. His remedy was to make the sorting algorithm monitor its recursion depth introspectively and if a preset depth was exceeded revert to a guaranteed O(n log n) sort, heapsort or perhaps mergesort. The dual mode algorithm was to be called 'introsort'. More recently it has been suggested that engineered median of three killers could be used to bring down a web-server in a denial of service attack. The current C++ STL sort method is an introsort implementation that reverts to heapsort making it easy to include an example of this approach in a test application, maybe.  Ralph Unden [5] has posted a Java class that outputs lists of median of three killer integer values and his paper provides further explanation of the problem with a minimum of mathematical analysis.&lt;/span&gt;&lt;/p&gt;&lt;p  style="font-weight: bold;font-family:arial;"&gt;&lt;span style="font-size:130%;"&gt;Relative Performance&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;Time taken to sort a list results from the data item comparisons and assignments used together with the amount of supporting processing carried out. Supporting processing includes computation of factors relating to the current list, updating indices, function calls and so on. Counting comparisons etc. gets a platform independent indication of performance but doing this can only be indicative. Suppose that swapping two items is done using a register as a temporary location for example, does this count as two assignments or three? Processing will take about 2/3 of the time needed to swap the items with one item stored temporarily in a buffer. Changes to the ratio of comparison cost to assignment cost and the effect of CPU cache misses are other factors.&lt;br /&gt;&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;The method preferred here is to show actual timings taken under the rules of the  Faster Than Quicksort game, which I think give a realistic assessment of relative performance at least for native code on the PC. These rules are simple and designed to make tests relate to working with records and objects rather than lists of numbers. The dynamic is different because even basic comparisons  take substantially longer than assignments.&lt;br /&gt;&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;The rules are: Sorting is to be done using a comparison function so that complex keys can substituted. The list holds references to data objects with at least a 32 byte memory footprint so that substantial portions of the in memory arrangement are not covered by a single CPU cache line. Object memory location must not have any sequential relationship with sorted list location. Armed with the timings we can then try to find out what went wrong using comparison counts and other statistics.&lt;/span&gt;&lt;/p&gt;&lt;p  style="font-weight: bold;font-family:arial;"&gt;&lt;span style="font-size:130%;"&gt;Algorithm Timings&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;Table 1 shows timings for sorting random order lists on a single integer key in milliseconds rounded to 3 decimal places. The rel. columns are performance relative to the fastest (tail call optimized) tcoQuicksort  figures in the first column. The test machine is a fairly typical desktop: dual core Pentium® at 3.3GHz, 2GB RAM. For each list size, sortings for 50 different lists, 25 generated using a Random() function and reversing the order of the list, are timed. Each timing uses an initial pass which is discarded and between 5 and 10 timed passes, fewer passes being used for larger lists (no worries, the test application does all this not me). The figure shown is the average but the maximum and minimum times were also recorded, any marked discrepancy leading to retesting to confirm or reject the initial timing.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_wwC0cvwYjJc/ScVaRjrgYpI/AAAAAAAAADE/QJBW1PIgWB0/s1600-h/Table1.gif"&gt;&lt;img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 400px; height: 221px;" src="http://2.bp.blogspot.com/_wwC0cvwYjJc/ScVaRjrgYpI/AAAAAAAAADE/QJBW1PIgWB0/s400/Table1.gif" alt="" id="BLOGGER_PHOTO_ID_5315754192862732946" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;Results were pretty much as expected. On random data all the sorting methods do considerably better than O(n log2 n) would suggest. No doubt other list configurations would restore the balance. The penalty for using full recursion over tail call optimization is quite small maximizing at 9% for a 4000 item list.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;Stable quicksort with its huge list-size buffer finally creeps ahead of its rivals for the largest list. It seems likely that this effect results from separate location of items equal to the partition element by this implementation, excluding them from the sublists passed to the next level. Random generation puts a proportion of records with equal keys in all the lists and for a large list their number may become significant. The maximum key value used is size – 1, hopefully getting a similar proportion of same keys for all list sizes. An in-place quicksort can  be implemented to provide separate location and exclusion [6] but some additional overhead is inevitable.&lt;br /&gt;&lt;br /&gt;The timings shown are probably a bit unfair on mergesort. Currently the problem is not lack of merge optimizations but may be the assembly language block-move routine used to deal with out of order sublists, still the same as for the Delphi Magazine article. It was always quite crude but changes to CPU architecture since P III have made it even less suitable. Java sort functions use mergesort with a list sized buffer and it will be interesting to see whether performance can be improved using current optimizations and a half-size buffer.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;The data for unoptimized TList.Sort shows that optimization is always worthwhile for random data particularly for smaller list sizes. Processing an in-order or reverse order list, Sort fairs better because the partition element is not swapped out to reduce partitioned elements by one. The effect of leaving the partition element in place, a design decision made in [6], needs further investigation.&lt;br /&gt;&lt;br /&gt;Timings for the C++ STL sort() function are not shown. It was clearly going to be impossible to get sort() from the current version of the STL to compile on the author's system without far more work than time available permitted, if at all. Data obtained using sort() from the template library supplied with Borland Developer Studio 2006 was so far out of kilter with other timings that it was felt that some effect other than the quality of the algorithm must be responsible. This is a pity because a comparison of timed performance on median of three killer lists would have been informative. As a substitute numbers of calls to the comparison function provide a stand in.&lt;br /&gt;&lt;/span&gt;&lt;/p&gt;&lt;p  style="font-weight: bold;font-family:arial;"&gt;&lt;span style="font-size:130%;"&gt;Median of Three Killers&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;Results are show in Table 2. The four left-hand columns show calls for lists of random data. Comparisons for median of three killer configurations are on the right.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_wwC0cvwYjJc/SccVgB5fpGI/AAAAAAAAADc/jLqMjSZykYs/s1600-h/Table+2.png"&gt;&lt;img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 400px; height: 136px;" src="http://1.bp.blogspot.com/_wwC0cvwYjJc/SccVgB5fpGI/AAAAAAAAADc/jLqMjSZykYs/s400/Table+2.png" alt="" id="BLOGGER_PHOTO_ID_5316241525143741538" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;Killer configurations have an adverse effect on tcoQuicksort and TList.Sort. The quicksort used by TList.Sort shows almost quadratic behaviour, a bit unfair seeing the implementation tested uses a middle element pivot not median of three. The effect on tcoQuicksort approximately doubles the number of comparisons needed to sort a list of the same size. The fully recursive version suffers the same fate: its  implementation is identical except for the tail call optimization. Taking list size to the next level, sorting a list with 2,048,000 elements tcoQuicksort uses  47,299,055 comparisons on random data and 106,537,288 comparisons on a killer sequence. The ratio remains approximately constant and is not quadratic. Mergesort and  the library sort() use fewer comparisons on a killer configuration than on random data, mergesort drastically so. Actual timings showed mergesort sorting the list on an integer key in better than 1/3 the time taken by the library function, tallying with the ratio of comparisons used, and this margin is of course even more substantial for a complex key.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-size:130%;" &gt;&lt;span style="font-family:arial;"&gt;Conclusions&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Quicksort provides fast sorting of randomly ordered data but can be affected adversely by certain data configurations. Optimizations may contain this problem for certain configurations or aggravate it for others. For the reason given tcoQuicksort uses around 66 million comparisons to sort a two million item list in reverse order as opposed to about 40 million used by  TList.Sort.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;Mergesort is a better all-rounder and can sort data ordered with an existing relationship to the required key faster than quicksort. Apparently it is also a Median of Three Killer-Killer! It may be possible to improve performance of the implementation tested here by writing a better block move routine but, because items located at opposite ends of the list to that required are moved late, mergesort can never surpass quicksort for sorting random ordered data.&lt;br /&gt;&lt;br /&gt;It seems likely that best proofing against adverse data combined with best sorting speed can be achieved using a  tail call optimized quicksort that checks for out of balance partitioning after the initial call and subsequently. An immediate switch to mergesort would reap the benefit of its superior efficiency on killer and other adverse configurations. A mergesort buffer can be allocated on the machine stack at any time during processing: a buffer only relates to a single recursion level and space beyond the stack pointer can be used by the merge routine on the way back to the root of the merge tree. The allocation overhead is minimal, ideally only a matter of checking stack headroom. When there is insufficient  headroom to to allocate an optimum size buffer an alternative merging routine that uses available space can be called.  If a language does not provide intrinsics for efficient stack allocation perhaps it should do so.&lt;br /&gt;&lt;br /&gt;The downside of using two algorithms is that code size is increased. It may be that double sorting time on some data configurations for large lists is acceptable using an optimized quicksort. Alternatively random selection of median of three elements might provide a simple alternative. A local randomization scheme need not be elaborate, say setting the initial seed using a value from the current machine clock and a linear congruential generator  on a smallish prime. This approach needs further investigation.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;References:&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="font-family:times new roman;"&gt;[1] Martin Humby. Buffered Sorting and Stack Buffers. Delphi Magazine Issue 113: January 2005.&lt;br /&gt;[2] C. A. R. Hoare,  Quicksort. Computer Journal Vol 5 (1): 10-15. 1962.&lt;br /&gt;[3] Robert Sedgewick, Implementing Quicksort Programs, Communications of the ACM Vol 21(10)  847–857 October 1978.&lt;br /&gt;[4] David R Musser, Introspective Sorting and Selection Algorithms, Computer Science Department, Rensselaer Polytechnic Institute, Troy, NY 12180, U.S.A.  1997.&lt;br /&gt;[5] Ralph Unden,  &lt;a href="http://ralphunden.net/?q=a-guide-to-introsort"&gt;&gt; here &lt;&lt;/a&gt;  and Implementierung und Untersuchung des introspektiven Sortieralgorithmus Introsort, Berufsakademie Stuttgart - Fachrichtung Informationstechnik, student paper April 2007&lt;br /&gt;[6] Jon L Bently, M Douglas McIlroy: Engineering a Sort Function. Software – Practice and Experience, Vol. 32(11), 1249-1265 November 1993.&lt;/span&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-2287416002061877503?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/2287416002061877503/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/03/test-this-is-code-more-code-end-test.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/2287416002061877503'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/2287416002061877503'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/03/test-this-is-code-more-code-end-test.html' title='Sorting Blog'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_wwC0cvwYjJc/ScVqdeURugI/AAAAAAAAADM/VxdqyZfzVL0/s72-c/Sorting+Demo.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-5829744373003478804</id><published>2009-03-16T14:52:00.000Z</published><updated>2009-03-17T23:17:21.378Z</updated><title type='text'>No Chance!</title><content type='html'>No chance! - of it working that is. Still get the blank page. With the XML stuff in the code, looks like another 'impedance mismatch' to me. In this case between the XHTML and Blogger's blog engine rather than an application trying to talk to some geriatric DBMS. To paraphrase James May: "Microspeak - Impedance mismatch, English - Cobblers!".&lt;br /&gt;&lt;br /&gt;The fact that it works in Preview but not otherwise takes this into the&lt;span style="font-style: italic;"&gt; really annoying&lt;/span&gt; category but got more important things to do than mess around with it. Found a stretchy version of Minima with the offer of replacing the title bar with a graphic. Computer generated sun, chaotic trees - seems appropriate maybe? What do you think?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-5829744373003478804?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/5829744373003478804/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/03/no-chance.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/5829744373003478804'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/5829744373003478804'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/03/no-chance.html' title='No Chance!'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5010874239602565935.post-802804169880011515</id><published>2009-03-14T21:52:00.001Z</published><updated>2009-03-15T18:38:38.382Z</updated><title type='text'>Changing Column Widths</title><content type='html'>&lt;span style="font-size:100%;"&gt;Don't intend to access this blog from my mobile or would probably have signed up to Twitter so decided to change the column widths to something more reasonable. Clicked on 'Customise' (My dictionary spells it Customize but what can you expect) Edit HTML. Copy the code for Minima, change some numbers, copy it back, click on  Preview and . . . Perfect! Just what I wanted! Nearly fell off chair, but then: View Blog: nothing, nix, nil, a blank page.&lt;br /&gt;&lt;br /&gt;Go back do it again, scratch head, get a cup of tea. Some time later . . . eventually get an error page: 'This blog does not have any posts. Please add at least one post in order to preview.' Well, they asked for one so here it is. Will it work now? Wouldn't put any money on it!&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5010874239602565935-802804169880011515?l=martinsjava.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://martinsjava.blogspot.com/feeds/802804169880011515/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://martinsjava.blogspot.com/2009/03/changing-column-widths.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/802804169880011515'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5010874239602565935/posts/default/802804169880011515'/><link rel='alternate' type='text/html' href='http://martinsjava.blogspot.com/2009/03/changing-column-widths.html' title='Changing Column Widths'/><author><name>Martin Humby</name><uri>http://www.blogger.com/profile/09454254047698665217</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_wwC0cvwYjJc/Sdky_ChyR_I/AAAAAAAAAEw/8WpRt2_BbXU/S220/ID.png'/></author><thr:total>0</thr:total></entry></feed>
