ADT’s, Collections/Generics and Iterators

Slides:



Advertisements
Similar presentations
Java Review Interface, Casting, Generics, Iterator.
Advertisements

1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
Stacks.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
1 ADTs, Collection, Iterable/Iterator Interfaces Collections and the Java Collections API The Collection Interface and its Hierarchy The Iterable and Iterator.
Interfaces A Java interface is a collection of constants and abstract methods with a name that looks like a class name, i.e. first letter is capitalized.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Exam 1 –Monday June 25 th –open Book / Open Notes –No Electronic Devices (calculators, laptops, etc) –Room Number: W –Time: 5:30pm to 8:00pm.
Topic 3 The Stack ADT.
Chapter 3 Introduction to Collections – Stacks Modified
Effective Java: Generics Last Updated: Spring 2009.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Data structures Abstract data types Java classes for Data structures and ADTs.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
1 CSCD 326 Data Structures I Software Design. 2 The Software Life Cycle 1. Specification 2. Design 3. Risk Analysis 4. Verification 5. Coding 6. Testing.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Click to edit Master text styles Stacks Data Structure.
Stacks and Queues. 2 Abstract Data Types (ADTs) abstract data type (ADT): A specification of a collection of data and the operations that can be performed.
Iterators.
Stacks Stack Abstract Data Type (ADT) Stack ADT Interface
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Sequences and Iterators
More on Java Generics Multiple Generic Types Bounded Generic Types
Chapter 20 Generic Classes and Methods
Methods Attributes Method Modifiers ‘static’
Chapter 12: Data Structures
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
Interfaces and Inheritance
Building Java Programs Chapter 14
HW-6 Deadline Extended to April 27th
Stacks and Queues.
structures and their relationships." - Linus Torvalds
Lecture 9 Concepts of Programming Languages
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Stacks.
Chapter 19 Generics Dr. Clincy - Lecture.
Stacks and Queues.
Stacks.
Stacks, Queues, and Deques
Conditional Statements
Lecture 26: Advanced List Implementation
Building Java Programs
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Generic programming in Java
Dynamic Data Structures and Generics
Example: LinkedSet<T>
CSE 501N Fall ‘09 13: Interfaces and Multiple Representation
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
Stacks.
Interator and Iterable
slides created by Alyssa Harding
Review: libraries and packages
Generics, Stack, Queue Based on slides by Alyssa Harding
Stacks, Queues, and Deques
Corresponds with Chapter 5
structures and their relationships." - Linus Torvalds
Stacks and Queues.
A type is a collection of values
Lecture 9 Concepts of Programming Languages
Presentation transcript:

ADT’s, Collections/Generics and Iterators Abstract Data Types (ADT’s) Collections / Stack Example Generics / Parameterized Classes Iterators Reading: L&C: 3.1-3.5, 7.1-7.2

Abstract Data Types (ADT’s) A data type is a set of values and operations that can be performed on those values The Java primitive data types (e.g. int) have values and operations defined in Java itself An Abstract Data Type (ADT) is a data type that has values and operations that are not defined in the language itself In Java, an ADT is implemented using a class or an interface

Abstract Data Types (ADT’s) An Abstract Data Type is a programming construct used to implement a data structure It is a class with methods for organizing and accessing the data that the ADT encapsulates The data storage strategy should be hidden by the API (the methods) of the ADT Interface (Methods and Constants) Class that uses an ADT Class that implements an ADT Data Storage

Abstract Data Types (ADT’s) The library code for Arrays.sort is designed to sort an array of Comparable objects: public static void sort (Comparable [ ] data) The Comparable interface defines an ADT There are no objects of Comparable “class” There are objects of classes that implement the Comparable interface (e.g. the Polynomial class in our Project 1) with a compareTo()method Arrays.sort only uses methods defined in the Comparable interface, i.e. compareTo()

Collections The Java Collections classes are ADT’s that can be used to create container objects to hold and manage access to a collection of other objects In Java, these classes can be used similarly to Python lists, tuples, and/or dictionaries However, Java Collections are defined in classes (not in the language itself) so the programmer defines the most appropriate methods for adding and accessing the data objects they contain The Collections classes are parameterized to allow identification of the type of their contents

Parameterized Classes To allow the compiler to type check the contents of a collection class, the class definition is parameterized, e.g. public class ArrayList<T> ... // fill in T Note: The letter used inside <> is a dummy and can be <T> like C++ or <E> like Oracle I prefer to use <T> based on C++ popularity and that is also what our textbook uses The type T must be a reference type - not primitive

Parameterized Classes Defining a parameterized class named Generic: public class Generic<T> { // use T in attribute declarations private T whatIsThis; // use T as a method’s parameter type public void doThis(T input) { … } // use T as a method’s return type public T doThat( … ) { return whatIsThis; }

Parameterized Classes Instantiating parameterized class Generic Generic<String> g = new Generic<String>(); Use methods with objects of the actual type g.doThis(“Hello”); String s = g.doThat( … ); The compiler can verify the correctness of any parameters passed or assignments of the return values No casting of data types should be required (If it is, you aren’t using generics correctly)

Parameterized Classes Use a known class - not the dummy letter T Generic<T> g = new Generic<T>(); // error Unless in a generic class where T is defined public class AnotherGenericClass<T> { … Generic<T> g = new Generic<T>(); // OK }

Parameterized Classes Sometimes we want to place a constraint on the class that can be used as T We may need T to be a type that implements a specific interface (e.g. Comparable) public class Sorter<T extends Comparable <T>> { // now our code can call compareTo // method on type T objects here }

Parameterized Classes Don’t omit an identified <type> in new code Generic g = new Generic(); // legacy code? Compiler will give incompatible type errors without an explicit cast (narrowing) String s = g.doThat( … ); // error String s = (String) g.doThat( … ); // OK Compiler will give unchecked warnings g.doThis(“Hello”); // warning

Parameterized Classes Can’t instantiate arrays of the generic data type without using a “trick” T [] t = new T[10]; // compile error T [] t = (T []) new Object[10]; // OK Can’t instantiate arrays of a parameterized class without using a slightly different “trick” ArrayList<String>[] a = (ArrayList<String>[]) new ArrayList[10]; Just casting a new Object[10] compiles OK but throws an exception at run time (Ouch!)

Parameterized Classes When you use either of the above “tricks”, the compiler will give you an “unchecked” warning Normally, we would “fix” our code to get rid of all compiler warnings but here we can’t “fix” it Use the compiler SuppressWarnings directive Place this line ahead of the method header @SuppressWarnings("unchecked") That directive will allow a “clean” compilation

An Example Collection: Stack A stack is a linear collection where the elements are added or removed from the same end The access strategy is last in, first out (LIFO) The last element put on the stack is the first element removed from the stack Think of a stack of cafeteria trays

A Conceptual View of a Stack Adding an Element Removing an Element Top of Stack

An Example Collection: Stack A stack collection has many possible uses: Reversing the order of a group of elements Push all elements onto a stack and pop them Evaluating Post-fix Expressions Text example which we will cover later in the course Back tracking in solution for a maze Push previous location on a stack to save it Pop previous location off the stack at a blind end We will discuss more uses for stacks later

Iterating over a Collection If we need to write code that retrieves all the elements of a collection to process them one at a time, we may use the “Iterator” design pattern from Design Patterns, Gamma et al. We call this iterating over the collection All Collection classes implement Iterable Collection<T> extends Iterable<T> The Iterable interface requires one method: Iterator<T> iterator();

Iterable Objects and Iterators An Iterable object allows you obtain an Iterator object to retrieve objects from it Iterator<T> iterator() returns an Iterator object to access this Iterable group of objects An Iterator object allows you to retrieve a sequence of all T objects using two methods: boolean hasNext() returns true if there are more objects of type T available in the group T next() returns the next T object from the group

Iterable Objects and Iterators All classes in the Java Collections library implement the Collection interface and are Iterable OR you can implement Iterable in any class that you define If myBookList is an object of an Iterable class named List that contains Book objects ArrayList<Book> myBookList = new ArrayList<Book>(); We can retrieve all the available Book objects from it in either of two ways:

Iterable Objects and Iterators We can obtain an Iterator object from an Iterable object and use it to retrieve all the items from the Iterable object indirectly: We can use the Java for-each loop to retrieve the contents of an Iterable object ArrayList<Book> bookList = new ArrayList<Book>(); // Code to add some Books to the bookList Iterator<Book> itr = bookList.iterator(); while (itr.hasNext()) System.out.println (itr.next()); for (Book myBook : bookList) System.out.println (myBook);

Iterable Objects and Iterators The Iterator hasNext() and next() methods do not modify the contents of the collection There is a third method called remove() that can be used to remove the last object retrieved by the next() method from the collection This is not always required for an application, but the method must be present to compile, so the code of the class that implements the iterator could throw an exception when remove is called