1 / 52

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. Proper representation of data helps achieve efficiency Representations and allowable operations on data are called its “data structure”

rupert
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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSC 332 – Algorithms and Data Structures Collections API Dr. Paige H. Meeker Computer Science Presbyterian College, Clinton, SC

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

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

  4. 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)

  5. Inheritance Review • The more general class is the superclass, the more specialized class is the subclass • All classes extend “Object”

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

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

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

  9. 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; } }

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

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

  12. 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(); }

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

  14. Interface Review • How is an interface different from a class?

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

  16. Interface Review • How is an interface different from a class? • All methods are abstract • All methods are public • No instance fields

  17. Interface Review The keyword “implements” indicates the class implements the interface type class ClassName implements Measurable { public double getMeasure() { implementation } Additional methods and fields }

  18. Interface Review • Classes can implement more than one interface type

  19. Polymorphism Review • When multiple classes implement an interface, each class implements the methods in a different way • How is the correct method invoked?

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

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

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

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

  24. Generic data structure protocol Most data structures follow the protocol of figure 6.1 of your text

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

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

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

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

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

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

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

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

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

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

  35. Iterator Interface • Contains: boolean hasNext() AnyType next() void remove() (View next slide) • Each collection defines its own implementation of the iterator interface.

  36. Iterator Interface Sample

  37. 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( ); }

  38. 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( ); }

  39. 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)

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

  41. 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( ); }

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

  43. 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()

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

More Related