Java Nuts and Bolts: Copy Constructors, Cloning, and Linked Structures
- Factories and the Recurring Need to Copy Objects
- Linked Java Structures
- Running the Supplied Code
I've often thought that mathematics is probably the worst taught of all subjects. If a student isn't lucky enough to build a good foundation early on, then he can look forward to a lifetime of unnecessary mathematical angst. It's a shame because mathematics is a lot like programming—often in both fields there is a multiplicity of solutions, which means that mathematics and programming exhibit many similarities.
The one thing that sets mathematicians and programmers apart is the ability to cut down on work while still getting the job done. I discuss this in detail in my upcoming eBook, but it's worth mentioning that economy of effort is a highly useful skill. The best programmers tend to rapidly get stuck into the hardest part of a given solution; this approach helps reduce the risk of a given project. An important tool in this ability to reduce risk is a deep understanding of the vernacular of a programming language—this can save much effort, i.e., if you take the time to learn the fine details, you'll reap the rewards later on.
Every programming language has its own special wrinkles, and knowledge of these can help in rapidly solving specific problems. In this article, I'll look at three areas of Java that often pass under the radar of programmers: copy constructors, cloning, and linked structures. Not fully understanding these areas of Java can result in reduced modularity and weak encapsulation—for example, not using copy constructors can easily result in unnecessary object instantiations. The same is true for cloning. Likewise, not using linked data structures can make for an unnecessarily complex data model.
Once you get to grips with these three concepts, you'll be programming in a less complex and more object-oriented spirit. So, without further ado, let's get started.
Factories and the Recurring Need to Copy Objects
The factory concept is a widely used design pattern in Java and other object-oriented programming languages. One of the design patterns that fulfils the needs of a factory is called the abstract factory. The purpose of the factory is for creating families of related or dependent objects without specifying concrete classes. Concrete classes are used to implement the specific object requirements. However, there is a lighter requirement than a factory that often arises where you simply want to copy an object.
When you copy an object, do you want an exact copy or do you want a new individual copy? In most cases, you will want a new individual copy and an easy way to do this is to use the copy constructor. Let's start the code section with the really simple class illustrated in Listing 1.
public class Document implements Copyable { private String name; private Date created; public Document(String docName, Date creationDate){ name = docName; created = new Date(creationDate); } public Document(Document original){ if (original == null){ System.out.println("Error - null object."); System.exit(0); } name = original.name; created = new Date(original.created); } public Object copy() { return new Document(name, created);} public String toString(){ return (name + ", " + created);} }
Listing 1 A Class with a Copy Constructor
In Listing 1, I present a very simple class that models a business document. The idea here is to use this class as a kind of template for different business document types, such as invoices, receipts, statements, and so on. If you run your own business, you get used to these pesky documents! So, when you want to instantiate an invoice object, you could use code such as that illustrated in Listing 2:
Document invoice = new Document("Invoice", new Date("April", 1, 2007));
Listing 2 Document Object Instantiation
In Listing 2, I create a document object instance. The document is simple: It is typed as an invoice and it has a creation date. Obviously, a real business document management system would have many more attributes, such as revision numbers, links to other documents, and so on.
So, nothing too surprising appears in Listings 1 and 2; you can now create objects of the Document class, and each such object is provided with an object reference. For example, in Listing 2 the reference is called invoice. A real-world application would typically include methods that allow operations specific to the object; for example, an invoice object would typically allow you to mark the underlying invoice as paid or unpaid. So, it's likely that you would subclass the Document class to implement the different business document classes. I haven't done any sub classing in this case, but you get the idea.
At this point, we have a bunch of instantiated Document objects as a result of running the code in Listing 3.
Document invoice = new Document("Invoice", new Date("April", 1, 2007)); Document receipt = new Document("Receipt", new Date("May", 11, 2007)); Document statement = new Document("Statement", new Date("January", 31, 2007));
Listing 3 A Bunch of Objects
Let's now suppose you want to create a copy of one of the objects in Listing 3. This is similar to the case when you want to make a copy of a Word document without changing the original. In other words, you want to create an independent copy—this is a job for the copy constructor. Listing 4 illustrates the copy constructor drawn from the code in Listing 1.
public Document(Document original) { if (original == null) { System.out.println("Error - null object."); System.exit(0); } name = original.name; created = new Date(original.created); }
Listing 4 The Copy Constructor
The clever part about Listing 4 is that it results in the instantiation of a new and independent object. This copy constructor can be invoked as follows:
Document anotherInvoice = new Document(invoice);
To determine if the objects in Listing 3 are unique with respect to the object produced by the copy constructor, you can just run the code shown in Listing 5.
System.out.println("Hash codes: " + invoice.hashCode() + " " + receipt.hashCode() + " " + statement.hashCode() + " " + anotherInvoice.hashCode());
Listing 5 Are the Objects Unique?
The code in Listing 5 produces the Listing 6 output on my desktop PC:
Hash codes: 4384790 9634993 1641745 11077203
Listing 6 Hash Codes Indicating Uniqueness
As you can see from Listing 6, each object has a unique hash code, which means what? Generally speaking, in as far as is reasonably practical, Java objects that are not equal have different hash codes. This is a useful property when you want to insert such objects in a hash table based data structure. Comparing hash codes in this fashion is what's called a shallow comparison. A deep comparison involves comparing data members for each object.
So much for the copy constructor. What about cloning? Suppose you don't want to implement a copy constructor but you still want to be able to copy a given object instance. Java supports a mechanism that allows this with the advantage of a somewhat lower footprint than a copy constructor. This is provided by a special purpose interface called Copyable. If you look at the first line in Listing 1, you'll see the line:
public class Document implements Copyable
This indicates that the class implements the Copyable interface with the following code in Listing 7:
public interface Copyable { public Object copy(); }
Listing 7 Implementation of the Copyable interface
The code in Listing 7 is very simple: It comprises a single method that returns a Java Object and that's all there is to it! So, what happens when you run the method in Listing 7? Listing 8 illustrates the code that calls the copy() method:
System.out.println("Creating a new document using the copy() method."); Document clonedDoc = (Document)anotherInvoice.copy(); System.out.println("A document was copied."); System.out.println("Original object hash code = " + anotherInvoice.hashCode()); System.out.println("Copied object hash code = " + clonedDoc.hashCode());
Listing 8 Copying a New Object Instance
It's very simple: The second line in Listing 8 invokes the copy() method. The remainder of the code just prints the hash code for the original object and the cloned object. As you can see in Listing 9, the hash codes indicate that the two objects are unique.
Creating a new document using the copy() method. A document was copied. Original object hash code = 11077203 Copied object hash code = 14576877
Listing 9 Unique Hash Code of a Cloned Object
As you can see, copying Java objects is pretty straightforward. Let's now take a look at the area of linked Java structures.