Csc 332 algorithms and data structures
This presentation is the property of its rightful owner.
Sponsored Links
1 / 52

CSC 332 – Algorithms and Data Structures PowerPoint PPT Presentation


  • 131 Views
  • Uploaded on
  • Presentation posted in: General

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”

Download Presentation

CSC 332 – Algorithms and Data Structures

An Image/Link below is provided (as is) to download presentation

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

CSC 332 – Algorithms and Data Structures

Collections API

Dr. Paige H. Meeker

Computer Science

Presbyterian College, Clinton, SC


Data structures

Data Structures

  • 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


Collections api

Collections API

  • 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 review

Inheritance Review

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)


Inheritance review1

Inheritance Review

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

  • All classes extend “Object”


Inheritance review2

Inheritance Review

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:

  • Specify added instance fields

  • Specify added methods

  • Override any methods as necessary.


Inheritance review3

Inheritance Review

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.


Inheritance review4

Inheritance Review

  • Subclasses have no access to private fields of the superclass

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

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

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


Inheritance review5

Inheritance Review

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;

}

}


Inheritance review6

Inheritance Review

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.


Inheritance review7

Inheritance Review

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.


Interface review

Interface Review

  • 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();

    }


Interface review1

Interface Review

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


Interface review2

Interface Review

  • How is an interface different from a class?


Interface review3

Interface Review

  • How is an interface different from a class?

    • All methods are abstract

      • They have a name, parameters, return type

      • They do NOT have implementation


Interface review4

Interface Review

  • How is an interface different from a class?

    • All methods are abstract

    • All methods are public

    • No instance fields


Interface review5

Interface Review

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

class ClassName implements Measurable {

public double getMeasure() {

implementation

}

Additional methods and fields

}


Interface review6

Interface Review

  • Classes can implement more than one interface type


Polymorphism review

Polymorphism Review

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

  • How is the correct method invoked?


Polymorphism review1

Polymorphism Review

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.


Polymorphism review2

Polymorphism Review

  • 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.


Goals of chapter 6

Goals of Chapter 6

  • 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


Data structures1

Data Structures

  • 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.


Generic data structure protocol

Generic data structure protocol

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


Iterators

Iterators

  • 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.


Iterators1

Iterators

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…

for(itr = v.first(); itr.isValid(); itr.advance())

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

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


Basic iterator design

Basic Iterator Design

  • 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


Inheritance based iterator design

Inheritance Based Iterator Design

  • 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


Csc 332 algorithms and data structures

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.


Csc 332 algorithms and data structures

An inheritance based design defines an interface; clients then program to the interface.


Csc 332 algorithms and data structures

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 design1

Inheritance Based Iterator Design

  • 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

Collections Interface

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


Collections interface1

Collections Interface

boolean isEmpty()

int size()

boolean add(AnyType x) //T=success,F=fail

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 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 Interface Sample


Now to print any collection

Now… to print any collection…

/**

* 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 collection1

Now… to print any collection…

/**

* 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

List 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

ListIterator

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


Listiterator1

ListIterator

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

LinkedList class

  • 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

LinkedList Supports:

void addLast(AnyType element)

void addFirst(AnyType element)

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

Stacks

  • Stacks restrict access to the most recently inserted item.

  • 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

Queues

  • Queues restrict access to the least recently inserted item.

  • 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

Homework

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

    HINT: Use chapter 16 as a reference!!


  • Login