Chapter 14
Chapter 14
Chapter 14
Chapter Contents
Using Inheritance to Implement a Sorted
List
Designing a Base Class
An Efficient Implementation of a Sorted List
• The Method add
2
Using Inheritance to Implement a
Sorted List
Have a revised SortedList method which
inherits from LList
public class SortedList extends LList
implements SortedListInterface
{ public boolean add(Comparable newEntry)
{
int newPosition = Math.abs(getPosition(newEntry));
return super.add(newPosition, newEntry);
} // end add
< Implementations of remove(anEntry) and getPosition(anEntry) go here. >
...
} // end SortedList
3
Using Inheritance to Implement a
Sorted List
Problem
• It inherits two methods which, if used could destroy the
order of the entries in a sorted list
public boolean add(int newPosition, Object newEntry);
public boolean replace(int givenPosition, Object newEntry);
Possible solutions
• Declare sorted list as an instance of
SortedListInterface
• Implement the add and replace within SortedList,
but have them return false
• Implement them but have them throw an exception
4
Designing a Base Class
6
Changes to LList
Declare firstNode and length to be protected
Provide protected methods
• setLength
• incrementLength
• decrementLength
Make getNodeAt protected
Make classNode and its constructors protected
Add protected methods
• setData
• getData
• setNextNode
• getNextNode
7
Designing a Base Class
9
The Method add
public boolean add(Comparable newEntry)
{ Node newNode = new Node(newEntry);
Node nodeBefore = getNodeBefore(newEntry);
if (isEmpty() || nodeBefore == null)
{ newNode.setNextNode(getFirstNode());
setFirstNode(newNode);
}
else
{ Node nodeAfter = nodeBefore.getNextNode();
newNode.setNextNode(nodeAfter);
nodeBefore.setNextNode(newNode);
} // end if
incrementLength();
return true;
} // end add
10
Efficiency
getPosition is O(n2)
Improved add method is O(n)
The class designer should use
inheritance and maintain efficiency
• Requires that base class provided
protected access to underlying data
structure
11