ADT List
ADT List
• Specifications for the ADT List
A li t id t i d t
• A list provides a way to organize data
– List of students – List of sales – List of lists
A li t h fi t l t d i b t it (th it h iti )
• A list has first , last , and in between items (the items has positions) • Operations on lists
– Add new entry – at end, or anywhere – Remove an item
– Remove all items – Replace an entry – Look at any entry
– Look for an entry of a specific value – Count how many entries
ADT List
ADT List
• To specify an ADT list
To specify an ADT list
– Describe its data
Specify the operations
– Specify the operations
• ADT list must be considered in general
f
– Not necessarily a list of strings
Specifications for the ADT List
DATA d i ti
• DATA description
• a collection of objects in a specific order and having the same data type. • The number of objects in the collection
• OPERATIONS specifications ( DRAFT )p ( )
– Add( newEntry ) Task: adds newEntry to the end of the list.
Input : newEntry is an object
Output: none
– Add ( newPosition , newEntry ) Task: adds newEntry at position, newPosition within the list
Input : newPosition as integer, newEntry is an object
object
Output: none
– Remove( givenPosition) Task: removes from the list the entry at position givenPosition
givenPosition.
Input: givenPosition is an integer .
Output: none
– Clear( ) Task: removes all entries from the list
Specifications for the ADT List
– Replace(givenPosition , newEntry) Task:replaces the entry at position givenPosition with newEntry .
Input : givenPosition is an integer , newEntry is an object
Output:none
– getEntry(givenPosition) Task: retrieves the entry at position givePosition in the list.
Input : givenPosition is an integer .
Output: return a reference to the entry at position i P iti
givenPosition.
– Contains(anEntry) Task: determines whether the list contains anEntry.
Input : anEntry is an object.
O tp t return true if anEntry is in the list or false if Output: return true if anEntry is in the list, or false if
not .
– getLength|() Task: gets the number of entries currently in the list.
Input: none .
Input : none .
Output: return the number of entries currently in the list as an int.
Specifications for the ADT List
Specifications for the ADT List
– isEmpty( ) Task: determines whether the list is empty
Input : none
Input : none .
Output: return true if the list is empty, or false if not.
– isFull( ) Task: determines whether the list is full
Input : none .
Output: return true if the list is full, or false if not.
– Display( )Display( ) Task:Task: display all entries that are in the list in the orderdisplay all entries that are in the list in the order
in which they occur, one per line.
Input : none .
Output: none.
Th b ifi ti d ft d t l t b th i i
• Example: The effect of ADT list operations
Example: The effect of ADT list operations
on an initially empty list
Potential Problem Operations
Potential Problem Operations
•
add
,
remove
,
replace
,
getEntry
work OK when valid
iti
i
position given
•
remove
,
replace
and
getEntry
not meaningful on empty
lists
• A list could become full, what happens to
add
?
•
Possible Solutions:
Possible Solutions:
• Assume the invalid situations will not occur
• Ignore the invalid situations
• Make reasonable assumptions act in predictable way
• Make reasonable assumptions, act in predictable way
• Return boolean value indicating success or failure of the
operation
Th
ti
an interface for the ADT list.
• After redefine the draft specifications and it is become complete we can starting to build the Java interface for the list ADT as follows:
/** an interface for the ADT list
/ an interface for the ADT list.
* entries in the list have positions that begin with 0. * /
public interface ListInterface{
/** T k dd t t th d f th li t i th l th b 1
/** Task: adds a new entry to the end of the list .increase the length by 1
*@ param newEntry the object to be added as a new entry
*@return true if the addition is successful ( list not full), false otherwise
*/
public boolean add (Object newEntry); public boolean add (Object newEntry);
/** Task: adds a new entry at a specified position within the list. * The list size increased by 1.
*@param newPosition an integer that specifies the desired position of the new entry ; *@param newEntry the object to be added as a new entry
*@return true if the addition is successful (newPosition >= 0 and newPosition <= * getLength (), and the list not full), or false if not
*/
public boolean add (int newPosition object newEntry); public boolean add (int newPosition, object newEntry);
an interface for the ADT list.
/** Task: removes the entry at a given position from the list. decrease the length by 1
*@param givenPosition an integer that indicates the position of the entry to be * removed;removed;
*@return either the entry at position givenPosition (if the list not empty && the
* givenPosition >=0 && the givenPosition< getLength()), otherwise return null
*/
public Object remove (int givenPosition); public Object remove (int givenPosition);
/** Task: Removes all entries from the list. */
public void clear();
/** Task: replaces the entry at a given position in the list.
*@param givenPosition an integer that indicates the position of the entry to be * replaced;
*@ E t th bj t th t ill l th t t th iti i P iti
*@param newEntry the object that will replace the entry at the position givenPosition *@return true if the replacement occurs (givenPosition >= 0 and givenPosition <
* getLength() and the list not empty), or false if either the list was empty
* or givenPosition is invalid
*/ */
an interface for the ADT list.
an interface for the ADT list.
/** Task: retrieves the entry at a given position in the list.
*@param givenPosition an integer that indicates the position of the desired entry;@param givenPosition an integer that indicates the position of the desired entry; *@return a reference to the indicated list entry, if (the list not empty and
* givenPosition >= 0 and givenPosition < getLength() and the entry found ,
* otherwise returns null
*//
public Object getEntry (int givenPosition);
/** Task: determines whether the list contains a given entry.
*@ E t th bj t th t i th d i d t
*@param anEntry the object that is the desired entry
*@return true if (the list not empty and the list contains anEntry), or false if not */
public boolean contains (Object anEntry);
/** Task: gets the length of the list.
*@return the integer number of entries currently in the list */
public int getLength();
an interface for the ADT list.
an interface for the ADT list.
/** Task: determines whether the list is empty.p y *@return true if the list is empty, or false if not */
public boolean isEmpty();
/** Task: determines whether the list is full. *@return true if the list is full, or false if not *//
public boolean isFull();
/** Task: displays all entries that are in the list, one per line, in the order in which p y p * they occur in the list.
*/
public void display();
Using the ADT List
bli l Li tCli t
public class ListClient
{ public static void main (String[] args)
{ testList(); } // end main public static void testList()
public static void testList()
{ ListInterface runnerList = new AList(); // has only methods in ListInterface
runnerList.add("16"); // winner
runnerList.add(" 4"); // second place
runnerList add("33"); // third place
runnerList.add( 33 ); // third place
runnerList.add("27"); // fourth place
runnerList.display();
} // end testList }} // end ListClient
• Observations about clients and List ADT
– Client can perform only operations from the ADT ListClient can perform only operations from the ADT List – Client must adhere to specifications
– Client cannot access data without an ADT operation
– Client can use the list – even though unable to access entries directly
If i l t ti i h d li t till li t i b f
– If implementation is changed, client still uses list in same way as before
Java Class Library: The Interface List
y
• The standard package contains a list interface – called List (java.util) M h d id d
• Methods provided:
public boolean add (Object newEntry)
public void add (int index Object newEntry)
public void add (int index, Object newEntry)
public Object remove (int index)
public void clear()
public Object set (int index Object anEntry) // like replace
public Object set (int index, Object anEntry) // like replace
public Object get (int index) // like getEntry
public boolean contains (Object anEntry)
public int size() // like getLength
p () g g
LIST Implementations
• List ADT can be implemented using:
Fi
d Si
A
i
l
t ti
– a Fixed-Size Array implementation
– Dynamic Array Expansion implementation
– a Vector implementation
– Linked-based implementation
List implementation using a Fixed-Size Array
Steps:
1. The Listinterface
2. Array- Based implementation
- AList class implements Listlnterface p - Data: An Array of Objects
An Integer counting the number of entries An Integer constant defines the size g
List implementation using a Fixed-Size Array
p
g
y
public class Alist implements ListInterface
{private Object entry[];
//
array of list entriesprivate int length;
//
current number of entries in listi i fi l i MAX SIZE 50
//
private static final int MAX_SIZE = 50;
//
max length of listpublic Alist() { length=0;
entry= new Object [ MAX SIZE ]; entry= new Object [ MAX_SIZE ]; }// end default constructor
public Alist ( int maxSize)
public Alist ( int maxSize) { length=0;
entry= new Object[ maxSize ];
}//
end user constructor}//
end user constructorList implementation using a Fixed-Size Array
p
g
y
public Boolean add ( Object newEntry) {
Boolean isSuccessful =true; If(! isFull())
If(! isFull()) {
entry [length]=newEntry; l th
length++; }
else
isSuccessful =false; return isSuccessful;
List implementation using a Fixed-Size Array
public boolean add (int newPosition, Object newEntry) { boolean isSuccessful =true;
if( (! isFull() && newPosition >=0)&&(newPosition<=length))( ( () ) ( g )) { makeRoom (newPosition);// private method that helps to shift items
//in order to make space for the new entry;
entry [newPosition]=newEntry; length++;
length++; }
else
isSuccessful =false; isSuccessful =false; return isSuccessful;
}//end add
private void makeRoom (int newPosition)
{ for (int index=length; index> newPosaition; index--) entry [index]=entry[index-1];
}//
}//end makeRoom
List implementation using a Fixed-Size Array
public Object remove (int givenPosition) { Object result=null; // returned value
if(! isEmpty() &&(givenPosition >=0)&&(givenPosition<length))( p y() (g ) (g g )) { result= entry [givenPosition];
if (givenPosition<length-1)
removeGap (givenPosition); // private method that helps to shift // it i d t
// items in order to remove space // after removing the entry;
length--; }}
return result;
}//end remove
G ( )
private void removeGap (int givenPosition)
{ for (int index= givenPosition; index <length-1;index++) entry [index]=entry[index+1];
}// d G
List implementation using a Fixed-Size Array
public boolean replace (int givenPosition, Object newEntry) { boolean isSuccessful = true;
If (! isEmpty() &&(givenPosition >= 0) && (givenPosition < length)) entry [givenPosition] = newEntry;
else
isSuccessful = false; return isSuccessful;
} // end replace
public Object getEntry (int givenPosition) {
Object result = null; // result to return
If (! isEmpty() &&(givenPosition >= 0) && (givenPosition < length)) result = entry [givenPosition];
return result;
} // end getEntry Dr. Abu-Arqoub
List implementation using a Fixed-Size Array
p
g
y
public boolean contains (Object anEntry)
{
boolean found = false;
for (int index = 0; !found && (index < length); index++){
if (anEntry.equals (entry [index]))
if (anEntry.equals (entry [index]))
found = true;
}
// end forreturn found;
return found;
}
//
end containspublic int getLength()
public int getLength()
{
return length;
List implementation using a Fixed-Size Array
public boolean isEmpty() public boolean isEmpty() { boolean itEmpty =false;
if (length ==0) itEmpty =true; itEmpty true; return itEmpty;
}//end isEmpty
public boolean isFull()
{ boolean itFull =false; // return length = = entry. length;
if (length= = entry. length) itF ll t
itFull =true; return itFull;
}// end isFull
public void display()
{ for (int index=0;index< length; Index++) System.out.println (entry [index]);
System.out.println (entry [index]);
}
CLIENT
CLIENT
•
CLIENT EXAMPLE:
CLIENT EXAMPLE:
public class ListClient {
Public static void main (String arg[]){
Public static void main (String arg[]){
ListInterface nameList =new Alist();
Name n1=new Name(“ali”,”ali”);
nameList.add(n1);
nameList.add (new Name (“sadam” ,”sadam”));
Using Dynamic Array Expansion
to implement the ADT List
•
One of the drawbacks of using fixed array size
g
y
to implement the List ADT is the limitation of
the list’s size.
O
l
hi
bl
i
h
•
One way to resolve this problem is to use the
dynamic expansion of the array.
•
Dynamic expansion of the array means: the
•
Dynamic expansion of the array means: the
elements of existing array is copied to a larger
one.
Dynamic Array Expansion
The dynamic expansion of an array copies the array's
contents to a larger second array
Dynamic Array Expansion
Dynamic Array Expansion
(a) an array;
(b) the same array with two references;
(b) the same array with two references;
A new implementation of a list
(d
i
i
)
(dynamic expansion)
• Revising the previous implementation we can
Revising the previous implementation we can
found that the following operations are affected:
– Isfull(): the list no more becomes full.
– The two add methods: calls the method that will
enlarge the array when it is become full.
• We need to add to the list’s implementation
class, two extra privet methods:
isArrayfull(): its implementation is the same as the
– isArrayfull(): its implementation is the same as the
method isfull() in the previous implementation.
A new implementation of a list
(d
i
i
)
(dynamic expansion)
/** Task: doubles the size of the array of list entries.*/
y
private void doubleArray(){
Object[] oldList = entry;
// save reference to array of list entriesint oldSize = oldList.Length;
// save old max size of arrayentry = new Object[2 * oldSize];
// double size of array // t i f ld t bi//copy entries from old array to new, bigger array
for (int index = 0; index < oldSize; index++)
entry [index] = oldList [index];
entry [index] oldList [index];
}
// end doubleArrayA new implementation of a list
(d
i
i
)
(dynamic expansion)
private boolean isArrayFull ()
p
y
()
{
boolean itFull= false;
// return length = = entry. length;
if (length = = entry. length)
itFull =true;
return itFull;
}
//
}
//
end isFull
public boolean isFull()
{
return false;
{
return false;
A new implementation of a list
(d
i
i
)
(dynamic expansion)
public boolean add (Object newEntry){
public boolean add (Object newEntry){
if (isArrayFull())
doubleArray();
doubleArray();
// add new entry after last current entry
Entry [length] = newEntry;
Entry [length] = newEntry;
length++;
return true;
return true;
}
// end add
A new implementation of a list
(d
i
i
)
(dynamic expansion)
public boolean add (int newPosition, Object newEntry)
{ boolean isSuccessful =true;
if( (newPosition <0)||(newPosition>length)) isSuccessful =false;
else { if (isArrayFull()) doubleArray();
makeRoom (newPosition( );// ) private method that helps to shift items in // order to make space for the new entry;
entry [newPosition]=newEntry; length++;
isSuccessful =true; }
Using a Vector to implement the ADT List
•
One way to let a list grow as needed is to
One way to let a list grow as needed is to
use dynamic array expansion, as the
previous implementation describes.
p
p
Another way uses an instance of Java’s
Vector class to represent the list’s
t i
entries.
•
The class vector provides the capabilities
f
th t
d d
i
ll
b t
of an array that expands dynamically, but
it hides the details of the process.
Vector Class
Vector Class
• Vector is a collection class . where its instance can
stores objects as array do.
• Vector double its size dynamically after it becomes full
• Vector class has many constructors:
• Vector class has many constructors:
– vector() // default constructor creates 10 locations. – Vector (initialSize);// with size
V t (i iti lSi i tSi ) // ith i d th b f – Vector (initialSize, incrementSize); // with size and the number of
// incremented locations when full
• vector class has methods similar to the methods in our
li
ADT
Vector class methods
Vector class methods
public void addElement (Object newElement); // to the end
p
(
j
);
public void insertElementAt (Object newElement, int index)
public void removeElementAt (int index);
public void removeAllElements ()
public void setElementAt (Object newElement, int index)
O
(
)
public Object elementAt (int index)
public boolean contains (Object anEntry)
public boolean isEmpty()
public boolean isEmpty()
public int size()
• **--No need length field (size())
--No need length field. (size())
Using a Vector to implement the ADT List
import java.util.vector;
public class VectorList implements ListInterface{ private Vector entry; // entries in list
public VectorList(){ entry = new Vector(); } // end default constructor
public VectorList (int initialSize)
p ( )
{ entry = new Vector (initialSize); } // end constructor
public boolean add (Object newEntry){
p ( j y){
entry.addElement (newEntry); return true;
} // end add
Using a Vector to implement the ADT List
public boolean add (int newPosition, Object newEntry)
{
boolean isSuccessful = true;
if (
P
iti
0) && (
P
iti
t
i
())
if (newPosition >= 0) && (newPosition <= entry.size())
entry.insertElementAt (newEntry, newPosition);
else
else
isSuccessful = false;
return isSuccessful;;
} // end add
Using a Vector to implement the ADT List
public Object remove (int givenPosition){
p
j
(
g
){
Object result = null;
// returned valueif
(! isEmpty() &&(givenPosition >= 0)&& (givenPosition < entry.size())) {{result = entry.elementAt (givenPosition);
entry.removeElementAt (givenPosition);
}
// end ifreturn result;
}
// dUsing a Vector to implement the ADT List
•
Clear :
Clear :
–
entry.removeAllElements();
•
Replace:
Replace:
–
entry.setElementAt (newEntry, givenPosition);
•
GetEntry
y
–
Result=entry.elementAt (givenPosition);
The pros and cons of using an Array to
i
l
t th ADT Li t
implement the ADT List
• The previous three implementations of the ADT list use an array to store the items in a list.
• Using an instance of Vector has the same advantages and
disadvantages as using dynamic array expansion but results in an implementation that is much easier to write.
• When you use an array or vector to implement the ADT list,
– Retrieving an entry is fast (advantage)g y ( g )
– Adding an entry at the end of a list is fast (advantage)
– Adding or removing an entry that is between other entries requires shifting elements in the array. (disadvantage)