1 / 52

# CSC 332 – Algorithms and Data Structures - PowerPoint PPT Presentation

CSC 332 – Algorithms and Data Structures. Collections API. Dr. Paige H. Meeker Computer Science Presbyterian College, Clinton, SC. Data Structures. Proper representation of data helps achieve efficiency Representations and allowable operations on data are called its “data structure”

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about ' CSC 332 – Algorithms and Data Structures' - rupert

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

### CSC 332 – Algorithms and Data Structures

Collections API

Dr. Paige H. Meeker

Computer Science

Presbyterian College, Clinton, SC

• Proper representation of data helps achieve efficiency

• Representations and allowable operations on data are called its “data structure”

• Data structures typically allow insertions, but restrict data access and deletions based on the type of structure

• Supporting Java library

• Provides collection of commonly used data structures

• Also provides some commonly used generic algorithms

• Uses inheritance

• Most reside in java.util

Inheritance is a way of extending classes by adding methods and fields. If you need a class for which a more general concept is already represented, you can “extend” the class

class SavingsAccount extends BankAccount {

new methods and fields

}

SavingsAccount will automatically inherit all methods and instance fields of the BankAccount class (like a deposit() or withdraw() method, for example)

• The more general class is the superclass, the more specialized class is the subclass

• All classes extend “Object”

Inheritance gives us the advantage of code reuse – you don’t have to reinvent the wheel each time you need a class to do something similar to something already done. To define a subclass:

• Override any methods as necessary.

Inheriting instance fields and methods:

• You can override methods of the superclass. If you specify a method with the same signature, it overrides the method of the same name in the superclass.

• You can inherit methods from the superclass (if not specifically overridden, it is inherited)

• You can define new methods

• You can never override instance fields – the subclass inherits all fields of the superclass

• Any new instance fields defined are present only in the subclass, not the superclass.

• NOTE: If you define an instance field in a subclass that has the same name as that of the superclass, it will be a NEW variable with a different value than that field in the superclass. This can lead to errors and is highly undesirable.

• Use the keyword “super” to call methods of the superclass

this.deposit() // uses deposit method of subclass

super.deposit() // uses deposit method of superclass.

To use the superclass’ constructor to help create the subclass, the constructor of the super class must be called as the first statement of the constructor of the subclass.

public class SavingsAccount extends BankAccount {

public SavingsAccount(double initBalance) {

super(initBalance);

transactionCount = 0;

}

}

Sometimes you need to convert between sub and super classes Because the subclass extends the superclass, it is a special case of the superclass and can be converted:

SavingsAccount acct = new SavingsAccount(500);

BankAccount newAcct = acct;

Object anObj = acct;

Now, all of these refer to the same object; however, anObj doesn’t know much about the object it’s storing and newAcct only knows the methods within BankAccount, not those in SavingsAccount.

To reverse directions, you can directly cast, but this can be dangerous if you’re wrong about the object. Use the instanceOf operator to protect against bad casts.

Finally, if you do not want someone to extend your class, declare it “final” as the String class – it can not be extended.

public final class String {..}

This also applies to methods, if you don’t want anyone to override your method.

• Interfaces are used to make code more general and reusable.

• An interface type declares a set of methods and their signatures

public interface Measureable {

double getMeasure();

}

• Declaration lists all methods that the interface type requires. “Measurable” on the previous slide, requires a single method but generally interfaces require multiple methods.

• How is an interface different from a class?

• How is an interface different from a class?

• All methods are abstract

• They have a name, parameters, return type

• They do NOT have implementation

• How is an interface different from a class?

• All methods are abstract

• All methods are public

• No instance fields

The keyword “implements” indicates the class implements the interface type

class ClassName implements Measurable {

public double getMeasure() {

implementation

}

}

• Classes can implement more than one interface type

• When multiple classes implement an interface, each class implements the methods in a different way

• How is the correct method invoked?

Measurable x;

Remember that object x refers to isn’t a Measurable but some class that implements the Measurable interface. When using an interface variable, all you can do is invoke the methods of the interface, not of the class you suspect the object to be.

• The idea that the actual type of the object determines the method is called polymorphism – behavior can change depending on the actual type of the object in question. Overloading a method is also an example of polymorphism.

• Provide a description (in general terms) of examples and applications of data structures

• Describe the basics of the Collections API

• Peek ahead into chapter 16 at some implementations

• Representation of data and the operations allowed on that data

• Allow component reuse

• Usually (but not always) store a collection of objects and provide methods to add, remove, or access those objects in specific ways.

Most data structures follow the protocol of figure 6.1 of your text

• Iterators are objects used to move through a collection. In the loop:

for (int i = 0; i < v.length; i++)

System.out.println(v[i]);

i is the iterator because it is the object used to control the iteration. We want a more generic iterator, though.

We want the code that performs access to the container to be independent of the type of container (think interface) – so the code would be replaced by something like…

System.out.println(itr.getData());

This code assumes methods of first(), isValid(), advance(), and getData() – useful methods for this purpose.

• Two methods:

• hasNext() – returns true if the iteration has not yet been exhausted

• next() – returns the next item in the collection and advances the current position.

(see fig’s 6.2 and 6.3 – next 2 slides)

Limitations? Can’t go backwards

• We have abstracted the idea of iteration into an iterator class; now, we need to define an iterator interface to give us even more freedom of coding design. This allows clients to program to the interface

The iterator method returns a reference to an Iterator object; the actual type turns out to be a “MyContainerIterator”. Since MyContainerIterator IS-A Iterator, this is safe to do.

Nowhere in “main” is there a reference to the actual iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

Inheritance Based Iterator Design iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

• The iterator() creates and returns an “Iterator” object whose actual type is unknown (we are using the interface type). This is known as a “factory method” A factory method creates a new concrete instance but returns it using a reference to the interface type.

• Now, code does not have to reference a specific type of iterator but can use the generic Iterator object provided by the interface.

Collections Interface iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

The collections interface represent a group of objects known as its elements. All containers within this interface support the following operations:

Collections Interface iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

boolean isEmpty()

int size()

boolean contains(Object x)

boolean remove(Object x) //T=success,F=fail

void clear() // empties container

Object [] toArray() <OtherType> OtherType [] toArray(OtherType [] arr) // returns array that contains references to all container items.

Java.util.Iterator<AnyType> iterator() // returns an iterator that will traverse the container

Iterator Interface iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

• Contains:

boolean hasNext()

AnyType next()

void remove()

(View next slide)

• Each collection defines its own implementation of the iterator interface.

Iterator Interface Sample iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

Now… to print any collection… iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

/**

* Print any collection using itr directly

*/

public static <AnyType> void printCollection( Collection<AnyType> c ) {

Iterator<AnyType> itr = c.iterator();

while( itr.hasNext() )

System.out.print( itr.next() + " " );

System.out.println( );

}

Now… to print any collection… iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

/**

* Print any collection using enhanced for loop

*/

public static <AnyType> void printCollection( Collection<AnyType> c ) {

for( AnyType val : c )

System.out.print( val + " " );

System.out.println( );

}

List Interface iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

• List – a collection of items in which the items have position

• Example: an array

• Extends the Collection interface and adds three methods:

• AnyType get(int idx)

• AnyType set(int idx)

• ListIterator<AnyType> listIterator(int pos)

ListIterator iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

The ListIterator interface is just like an Iterator except it is bidirectional – we can both advance and retreat!

ListIterator iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

package weiss.util;

/**

* ListIterator interface for List interface.

*/

public interface ListIterator<AnyType> extends Iterator<AnyType>

{

/**

* Tests if there are more items in the collection when iterating in reverse.

* @return true if there are more items in the collection when traversing in reverse.

*/

boolean hasPrevious( );

/**

* Obtains the previous item in the collection.

* @return the previous (as yet unseen) item in the collection when traversing in reverse.

*/

AnyType previous( );

/**

* Remove the last item returned by next or previous. Can only be called once after next or previous.

*/

void remove( );

}

LinkedList class iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

• Two implementations of the List Interface – ArrayList and LinkedList

• Vector (a depreciated class) also implements LinkedList

• LinkedLists store objects in a node that contains the object and a reference to the next node in the list

LinkedList Supports: iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

AnyType getFirst() // returns 1st element

AnyType element() // returns 1st element

AnyType getLast()

AnyType removeFirst() //removes 1st element

AnyType remove() //removes 1st element

AnyType removeLast()

Stacks iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

• FILO (First in, Last out)

• Operations take constant time.

• Natural operations are:

• Push (inserts item onto stack)

• Pop (removes top item of the stack)

• Top (returns top item without removal)

• Important for use in compiler design, to check unbalances, implement method calls in most programming languages, evaluates expressions, etc.

Queues iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

• FIFO (First in, First out)

• Operations take constant time.

• Natural operations are:

• Enqueue (inserts item at the back of the line)

• Dequeue (removes item at front of the line)

• GetFront (returns front item without removal)

• Important for use in any design where there is a feeling of “first come, first serve”

Homework iterator type; only to an “Iterator”. This HIDES the implementation (the client does not necessarily know about “MyContainerIterator” and PROGRAMS TO AN INTERFACE.

• See the labs section for the next programming assignment (So much to do… so little time)

HINT: Use chapter 16 as a reference!!