csc 332 algorithms and data structures
Skip this Video
Download Presentation
CSC 332 – Algorithms and Data Structures

Loading in 2 Seconds...

play fullscreen
1 / 52

CSC 332 – Algorithms and Data Structures - PowerPoint PPT Presentation

  • Uploaded on

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.
Download Presentation

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

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) {


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() {



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 are objects used to move through a collection. In the loop:

for (int i = 0; i < v.length; 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…

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


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
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 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 [] toArray(OtherType [] arr) // returns array that contains references to all container items.

Java.util.Iterator 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.
now to print any collection
Now… to print any collection…


* Print any collection using itr directly


public static void printCollection( Collection c ) {

Iterator itr = c.iterator();

while( itr.hasNext() )

System.out.print( + " " );

System.out.println( );


now to print any collection1
Now… to print any collection…


* Print any collection using enhanced for loop


public static void printCollection( Collection 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 listIterator(int pos)

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


package weiss.util;


* ListIterator interface for List interface.


public interface ListIterator extends Iterator



* 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 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 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”
  • See the labs section for the next programming assignment (So much to do… so little time)

HINT: Use chapter 16 as a reference!!