CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.

Slides:



Advertisements
Similar presentations
Linked Lists Linear collections.
Advertisements

COSC 1P03 Data Structures and Abstraction 10.1 The List If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
List Implementations That Use Arrays Chapter 5. 2 Chapter Contents Using a Fixed-Size Array to Implement the ADT List An Analogy The Java Implementation.
Iterators Chapter 7. Chapter Contents What is an Iterator? A Basic Iterator Visits every item in a collection Knows if it has visited all items Doesn’t.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
12-Jul-15 Lists in Java Part of the Collections Framework.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
Arrays And ArrayLists - S. Kelly-Bootle
1 Lecture 09 Iterators and Enumerations Reading for these lectures: Weiss, Section Iterator Interface. Much better is: ProgramLive, Section 12.3.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
1/20/03A2-1 CS494 Interfaces and Collection in Java.
1 Chapter 20 Lists, Stacks, Queues Lecture 7 Dr. Musab Zghoul برمجة هيكلية.
CHAPTER 5 ArrayLists.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
CS 367 Introduction to Data Structures Lecture 4.
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
Lists Chapter 4. 2 Chapter Contents Specifications for the ADT List Redefining the Specifications Using the ADT List Using a List Is Like Using a Vending.
Chapter 2 Collections. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related.
CS 367 Introduction to Data Structures Lecture 3.
CS 367 Introduction to Data Structures Lecture 5.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
CS 367 Introduction to Data Structures Charles N. Fischer Fall s367.html.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
CS 46B: Introduction to Data Structures July 21 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 18 List ADT Animated Version.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 9 Doubly Linked Lists and Ordered Lists Lecture.
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Problem of the Day  Simplify this equation: (x - a) * (x - b) * (x - c) * … * (x - z)
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
An Array-Based Implementation of the ADT List
Linked Data Structures
EKT472: Object Oriented Programming
Iterators.
List Representation - Array
Building Java Programs
Programming in Java Lecture 11: ArrayList
ArraySet Methods and ArrayIterator
slides created by Ethan Apter
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
ArrayList Collections.
Programming II (CS300) Chapter 07: Linked Lists and Iterators
slides created by Ethan Apter
ArrayLists 22-Feb-19.
COMPUTER 2430 Object Oriented Programming and Data Structures I
Building Java Programs
Programming II (CS300) Chapter 07: Linked Lists
slides created by Ethan Apter and Marty Stepp
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18

Let’s build a BagAST using an array of Objects. Arrays are simple to use but also have a fixed size.

public class ArrayBag implements BagADT { /* Local data to implement a Bag */ /* One or more constructors */ /* Implementations for add, remove, isEmpty and clone */ }

public class ArrayBag implements BagADT { private Object[] items; private int itemCount; private final int INIT_SIZE; /* One or more constructors */ /* Implementations for add, remove, isEmpty and clone */ }

public class ArrayBag implements BagADT { private Object[] items; private int itemCount; private final int INIT_SIZE; public ArrayBag() { itemCount = 0; INIT_SIZE = 100; items = new Object[INIT_SIZE]; } /* Implementations for add, remove, isEmpty and clone */ }

public class ArrayBag implements BagADT { private Object[] items; private int itemCount; private final int INIT_SIZE; public ArrayBag() { … } public boolean isEmpty() { return (itemCount == 0); } }

public class ArrayBag implements BagADT { private Object[] items; private int itemCount; private final int INIT_SIZE; public ArrayBag() { … } public boolean isEmpty() { … } public void add(Object item) { if (item == null) throw new NullPointerException(); if (itemCount >= INIT_SIZE) throw new Error(); items[itemCount] = item; itemCount++; }}

public class ArrayBag implements BagADT { private Object[] items; private int itemCount; private final int INIT_SIZE; public ArrayBag() { … } public boolean isEmpty() { … } public void add(Object item) {…} public Object remove() throws NoSuchElementException { if (itemCount == 0) throw new NoSuchElementException(); else { itemCount--; return items[itemCount] ; } }

public class ArrayBag implements BagADT { private Object[] items; private int itemCount; private final int INIT_SIZE; public ArrayBag() { … } public boolean isEmpty() { … } public void add(Object item) {…} public Object remove() throws NoSuchElementException {…} public ArrayBag clone() { ArrayBag copy = new ArrayBag(); copy.itemCount = itemCount; copy.items = items.clone(); return copy; } }

Examples of using ArrayBag: ArrayBag bag = new ArrayBag(); bag.add(1); bag.add(2); bag.add(3); bag.add(1); bag.add(2); bag.add(3); printBag(bag); printBag(bag); int item = (int) bag.remove(); int item = (int) bag.remove(); System.out.println(item); System.out.println(item); Output is:3213

Using the Object class in BagADT can be problematic You have to type-cast all objects returned by remove () (Why?) It is hard to enforce a uniform type in a bag. Bag declarations are uninformative. (All bags are essentially the same)

Java Generics Generics allow you to add a type parameter to an interface or class: BagADT or ArrayBag

When a type is declared, a class name replaces the type parameter: ArrayBag or ArrayBag Only the declared type can be inserted. Removed items need not be type-cast.

public interface BagADT { void add(E item); E remove () throws NoSuchElementException ; boolean isEmpty(); BagADT clone(); }

public class ArrayBag implements BagADT { /* Local data to implement a Bag */ /* One or more constructors */ /* Implementations for add, remove, isEmpty and clone */ }

public class ArrayBag implements BagADT { private E[] items; private int itemCount; private final int INIT_SIZE; /* One or more constructors */ /* Implementations for add, remove, isEmpty and clone */ }

public class ArrayBag implements BagADT { private E[] items; private int itemCount; private final int INIT_SIZE; public ArrayBag() { itemCount = 0; INIT_SIZE = 100; // Kludge alert! items = (E[]) new Object[INIT_SIZE]; } /* Implementations for add, remove, isEmpty and clone */ }

public class ArrayBag implements BagADT { private E[] items; private int itemCount; private final int INIT_SIZE; public ArrayBag() { … } public boolean isEmpty() { return (itemCount == 0); } }

public class ArrayBag implements BagADT { private E[] items; private int itemCount; private final int INIT_SIZE; public ArrayBag() { … } public boolean isEmpty() { … } public void add(E item) { if (item == null) throw new NullPointerException(); if (itemCount >= INIT_SIZE) throw new Error(); items[itemCount] = item; itemCount++; }}

public class ArrayBag implements BagADT { private E[] items; private int itemCount; private final int INIT_SIZE; public ArrayBag() { … } public boolean isEmpty() { … } public void add(Object item) {…} public E remove() throws NoSuchElementException { if (itemCount == 0) throw new NoSuchElementException(); else { itemCount--; return items[itemCount] ; } }

public class ArrayBag implements BagADT { private E[] items; private int itemCount; private final int INIT_SIZE; public ArrayBag() { … } public boolean isEmpty() { … } public void add(Object item) {…} public Object remove() throws NoSuchElementException {…} public ArrayBag clone() { ArrayBag copy = new ArrayBag (); copy.itemCount = itemCount; copy.items = items.clone(); return copy; } }

printBag becomes: public void printBag(BagADT myBag){ BagADT temp = myBag.clone(); while(! temp.isEmpty()) { System.out.println(temp.remove()); } }

Examples of using ArrayBag in Generic form: ArrayBag bag = new ArrayBag (); bag.add(1); bag.add(2); bag.add(33); bag.printBag(bag); int item = bag.remove(); // No casting! System.out.println(item); Output is:332133

List ADT A List is an ordered collection of items. Each item has a position, starting at 0. Item: “a” “b” “c” “d” “e” Position:

Like an array, a list can be indexed. But, a list can grow or shrink in size. A size of zero (an empty list) is allowed.

Operations in a ListADT void add(E item) Add where? At right end of list. void add(int pos, E item) add add does not overwrite items, so list size grows. pos Valid values for pos are 0 <= pos <= size()-1

boolean contains(E item) E Is E already in the list? equals(item) Use equals(item) to test membership. int size() Zero size is OK. boolean isEmpty() size() == 0 Same as size() == 0

E get(int pos) pos Return value at pos. Non-destructive. 0 <= pos <= size()-1 Requires 0 <= pos <= size()-1 E remove(int pos) pos Remove and return value at pos. Is destructive. 0 <= pos <= size()-1 Requires 0 <= pos <= size()-1

Error Conditions null Can null be added? null We’ll ignore adds of null. containsnull contains must handle null correctly. pos Bad pos values will throw IndexOutOfBounds getremove pos get or remove on empty list is really a bad pos error

Interface definition for ListADT public interface ListADT { void add(E item); void add(int pos, E item); boolean contains(E item); int size( ); boolean isEmpty( ); E get(int pos); E remove(int pos); }

Using the ListADT Write a method that reverses the contents of a list. Thus (1,2,3,4) becomes (4,3,2,1). Choose the approach you will take before writing code.

One approach: Move 2 nd from right to very end. Then 3 rd from right to very end. … Finally, farthest from right (leftmost) To very end. (11,22,33,44) (11,22,44,33) (11,44,33,22) (44,33,22,11)

Java code to reverse a List void reverse(){ for (int i = size() - 2; i >= 0; i--) add(remove(i)); } Why start i at size() - 2 ? Are “corner cases” (lists of size 0 or 1) handled properly?

Let’s build a ListAST using an array. Arrays are simple to use but also have a fixed size. We’ll expand the list as necessary when the list grows.

public class SimpleArrayList implements ListADT { /* Local data to implement a list*/ /* One or more constructors */ /* Implementations for add, remove, isEmpty, size, get and contains */ }

public class SimpleArrayList implements ListADT { private E[] items; private int itemCount; private final int INIT_SIZE; /* One or more constructors */ /* Implementations for interface methods */ }

public class SimpleArrayList implements ListADT { private E[] items; private int itemCount; private final int INIT_SIZE; public SimpleArrayList() { itemCount = 0; INIT_SIZE = 100; items = (E[]) new Object[INIT_SIZE]; } /* Implementations for interface methods */ }

public class SimpleArrayList implements ListADT { private E[] items; private int itemCount; private final int INIT_SIZE; public SimpleArrayList() {... }... public boolean isEmpty() { return (itemCount == 0); } }

public class SimpleArrayList implements ListADT { private E[] items; private int itemCount; private final int INIT_SIZE; public SimpleArrayList() {... }... public int size() { return itemCount; } }

public class SimpleArrayList implements ListADT {... public void add(E item) { if (item == null) throw new NullPointerException(); if (itemCount == items.length) expandArray(); items[itemCount] = item; itemCount++; }}

public class SimpleArrayList implements ListADT {... private void expandArray() { E[] newArray = (E[]) new Object[itemCount*2]; for (int k = 0; k implements ListADT {... private void expandArray() { E[] newArray = (E[]) new Object[itemCount*2]; for (int k = 0; k < itemCount; k++) { newArray[k] = items[k]; } items = newArray; } }}

public class SimpleArrayList implements ListADT { private Object[] items; private int itemCount; private final int INIT_SIZE; public ArrayBag() { … } public boolean isEmpty() { … } public void add(Object item) {…} public Object remove() throws NoSuchElementException { if (itemCount == 0) throw new NoSuchElementException(); else { itemCount--; return items[itemCount] ; } }

public class SimpleArrayList implements ListADT {... public void add(int pos, E item){ if (item == null) throw new NullPointerException(); if (itemCount == items.length) expandArray(); if (pos itemCount) throw new IndexOutOfBoundsException(); // move items over and insert new item for (int k = itemCount; k > pos; k--) items[k] = items[k-1]; items[pos] = item; itemCount++; }}

public class SimpleArrayList implements ListADT {... public E get(int pos) { // check for bad pos if (pos = itemCount) { throw new IndexOutOfBoundsException(); } // return the item at pos return items[pos]; }; }

public class SimpleArrayList implements ListADT {... public E remove(int pos) { // check for bad pos if (pos = itemCount) throw new IndexOutOfBoundsException(); // get the item to be removed from pos E ob = items[pos]; // move items over to fill removed pos for (int k = pos; k implements ListADT {... public E remove(int pos) { // check for bad pos if (pos = itemCount) throw new IndexOutOfBoundsException(); // get the item to be removed from pos E ob = items[pos]; // move items over to fill removed pos for (int k = pos; k < itemCount-1; k++) items[k] = items[k+1]; // decrease the number of items itemCount--; // return the removed item return ob; } }

public class SimpleArrayList implements ListADT {... public boolean contains(E item){ // null values are not allowed in the list if (item == null) return false; for (int i=0; i implements ListADT {... public boolean contains(E item){ // null values are not allowed in the list if (item == null) return false; for (int i=0; i < itemCount; i++){ if (items[i].equals(item)) return true; } return false; }}

A Very Useful Auxiliary Method In testing and debugging ADTs, it is very useful to see their contents. In Java, you may add a “toString” method to a class. When Java tries to print an object, it calls toString to obtain a string representation of the object, and then prints that string.

toString methods need not be very complex to be useful: public String toString() { String result = "("; for (int k = 0; k < itemCount; k++) { if (k==0) result += items[0].toString() ; else result += ("," + items[k].toString()); } return result + ")"; }

Are lists of lists allowed? They are, and can be very useful. Consider: SimpleArrayList > LL = new SimpleArrayList >(); SimpleArrayList L3 = new SimpleArrayList (); SimpleArrayList L4 = new SimpleArrayList ();

L3.add(123); L3.add(234); L3.add(345); System.out.println(L3); L4.add(456); L4.add(567); System.out.println(L4); LL.add(L3); LL.add(L4); System.out.println(LL); What is printed? (123,234,345) (456,567) ((123,234,345),(456,567))

Iterators Most ADTs in Java can provide an iterator object, used to traverse all the data in an ADT.

Iterator Interface public interface Iterator { boolean hasNext(); E next(); void remove(); // Optional }

Getting an Iterator You get an iterator from an ADT by calling the method iterator(); Iterator iter = myList.iterator();

Now a simple while loop can process each data value in the ADT: while(iter.hasNext()) { process iter.next() }

A Simple Print method for Lists void printArrayList(){ Iterator iter = this.iterator(); while(iter.hasNext()){ System.out.print(iter.next()+" "); } System.out.println(); }

Adding Iterators to SimpleArrayList is easy First, we add the iterator() method to SimpleArrayList : public Iterator iterator(){ return new ArrayListIterator (this) ; }

Then we implement the iterator class for Lists: import java.util.*; public class ArrayListIterator implements Iterator { // *** fields *** private SimpleArrayList list; private int curPos; public ArrayListIterator( SimpleArrayList list) { this.list = list; curPos = 0; }

public boolean hasNext() { return curPos < list.size(); } public E next() { if (!hasNext()) throw new NoSuchElementException(); E result = list.get(curPos); curPos++; return result; } public void remove() { throw new UnsupportedOperationException(); }

Empty vs. Null In Java all objects are accessed through a reference. A reference may be null. This is not the same as a data object that has nothing in it. Consider String str1 = “”; String str2 = null; str1 references something (the empty string) str2 references nothing.