CSC 205/206/405
Professor Stearns
Design Issues - Collection Class Semantics
Issue 1 - reference or value?
- The collection holds a pointer to the element. (reference semantics)
The element isn't copied so performance is better. The client code
retains responsibility for the element.
- The collection holds a copy of the element (value semantics)
This is safer but performance suffers.
- Java only supports reference semantics but your design can
clone every element that is retrieved from the collection.
Issue 2 - shallow vs deep copies
If an object is shallow copied, the new object is bit-wise identical
to the original object. Shallow copies are fast but can cause memory
allocation issues.
If an object is deep copied, the new object contains copies of all
instance variables. The copy is done recursively until only primitive
objects are copied.
Deep copies are safe but slower; for large collections they are
infeasible.
Notes:
- Most commercial class libraries use reference semantics.
But check before you use them; it's amazing that some manuals don't
even answer the question. Write a program to find out!
- Be consistent in your own design work.
All collection classes should work the same way.
WRITE DOWN your decisions in the definition files.
- The C++ default copy constructor makes shallow copies.
Ask about my senior project horror stories.
- There is no such thing as a copy constructor in Java.
- In a reference semantics environment, all collection classes
must support reference counting.
If you didn't learn this in 103, find out about it.
Last updated on 4/24/00